package com.brilliance.isc.automatic.engine.config;

import com.alibaba.fastjson.JSON;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.TypeConversionException;
import org.apache.camel.spi.TypeConverterRegistry;
import org.apache.camel.support.TypeConverterSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Objects;

@ConditionalOnClass(CamelContext.class)
@Component
public class CustomTypeConverterConfig {
    @Autowired(required = false)
    private CamelContext camelContext;

    @PostConstruct
    public void init() {
        if (Objects.isNull(camelContext)) {
            return;
        }
        CustomTypeConverter customTypeConverter = new CustomTypeConverter();
        TypeConverterRegistry typeConverterRegistry = camelContext.getTypeConverterRegistry();
        typeConverterRegistry.addFallbackTypeConverter(customTypeConverter, true);
    }

    private static class CustomTypeConverter extends TypeConverterSupport {
        @Override
        public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException {
            if (value instanceof JSON) {
                try {
                    return JSON.toJavaObject((JSON) value, type);
                } catch (Exception e) {
                    return null;
                }
            }
            return null;
        }
    }
}
