
package org.mule.modules.avalara.config;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.mule.DefaultMuleEvent;
import org.mule.DefaultMuleMessage;
import org.mule.api.MessagingException;
import org.mule.api.MuleContext;
import org.mule.api.MuleEvent;
import org.mule.api.MuleException;
import org.mule.api.MuleMessage;
import org.mule.api.construct.FlowConstruct;
import org.mule.api.construct.FlowConstructAware;
import org.mule.api.context.MuleContextAware;
import org.mule.api.expression.ExpressionManager;
import org.mule.api.lifecycle.Disposable;
import org.mule.api.lifecycle.Initialisable;
import org.mule.api.lifecycle.InitialisationException;
import org.mule.api.lifecycle.Startable;
import org.mule.api.lifecycle.Stoppable;
import org.mule.api.processor.MessageProcessor;
import org.mule.api.registry.RegistrationException;
import org.mule.api.transformer.DataType;
import org.mule.api.transformer.Transformer;
import org.mule.api.transformer.TransformerException;
import org.mule.config.i18n.CoreMessages;
import org.mule.config.i18n.MessageFactory;
import org.mule.modules.avalara.AvalaraModule;
import org.mule.modules.avalara.TextCaseType;
import org.mule.transformer.TransformerTemplate;
import org.mule.transformer.types.DataTypeFactory;
import org.mule.transport.NullPayload;
import org.mule.util.TemplateParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * ValidateAddressMessageProcessor invokes the {@link org.mule.modules.avalara.AvalaraModule#validateAddress(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, int, java.lang.String, java.lang.String, org.mule.modules.avalara.TextCaseType, boolean, boolean, java.util.Date)} method in {@link AvalaraModule }. For each argument there is a field in this processor to match it.  Before invoking the actual method the processor will evaluate and transform where possible to the expected argument type.
 * 
 */
public class ValidateAddressMessageProcessor
    implements FlowConstructAware, MuleContextAware, Disposable, Initialisable, Startable, Stoppable, MessageProcessor
{

    private Object line1;
    private String _line1Type;
    private Object line2;
    private String _line2Type;
    private Object line3;
    private String _line3Type;
    private Object city;
    private String _cityType;
    private Object region;
    private String _regionType;
    private Object country;
    private String _countryType;
    private Object postalCode;
    private String _postalCodeType;
    private Object addressCode;
    private String _addressCodeType;
    private Object taxRegionId;
    private int _taxRegionIdType;
    private Object latitude;
    private String _latitudeType;
    private Object longitude;
    private String _longitudeType;
    private Object textCase;
    private TextCaseType _textCaseType;
    private Object coordinates;
    private boolean _coordinatesType;
    private Object taxability;
    private boolean _taxabilityType;
    private Object date;
    private Date _dateType;
    private static Logger logger = LoggerFactory.getLogger(ValidateAddressMessageProcessor.class);
    /**
     * Module object
     * 
     */
    private Object moduleObject;
    /**
     * Mule Context
     * 
     */
    private MuleContext muleContext;
    /**
     * Mule Expression Manager
     * 
     */
    private ExpressionManager expressionManager;
    /**
     * Mule Pattern Info
     * 
     */
    private TemplateParser.PatternInfo patternInfo;
    /**
     * Flow construct
     * 
     */
    private FlowConstruct flowConstruct;
    /**
     * Variable used to track how many retries we have attempted on this message processor
     * 
     */
    private AtomicInteger retryCount;
    /**
     * Maximum number of retries that can be attempted.
     * 
     */
    private int retryMax;

    /**
     * Obtains the expression manager from the Mule context and initialises the connector. If a target object  has not been set already it will search the Mule registry for a default one.
     * 
     * @throws InitialisationException
     */
    public void initialise()
        throws InitialisationException
    {
        retryCount = new AtomicInteger();
        expressionManager = muleContext.getExpressionManager();
        patternInfo = TemplateParser.createMuleStyleParser().getStyle();
        if (moduleObject == null) {
            try {
                moduleObject = muleContext.getRegistry().lookupObject(AvalaraModuleLifecycleAdapter.class);
                if (moduleObject == null) {
                    throw new InitialisationException(MessageFactory.createStaticMessage("Cannot find object"), this);
                }
            } catch (RegistrationException e) {
                throw new InitialisationException(CoreMessages.initialisationFailure("org.mule.modules.avalara.config.AvalaraModuleLifecycleAdapter"), e, this);
            }
        }
    }

    public void start()
        throws MuleException
    {
    }

    public void stop()
        throws MuleException
    {
    }

    public void dispose() {
    }

    /**
     * Set the Mule context
     * 
     * @param context Mule context to set
     */
    public void setMuleContext(MuleContext context) {
        this.muleContext = context;
    }

    /**
     * Sets flow construct
     * 
     * @param flowConstruct Flow construct to set
     */
    public void setFlowConstruct(FlowConstruct flowConstruct) {
        this.flowConstruct = flowConstruct;
    }

    /**
     * Sets the instance of the object under which the processor will execute
     * 
     * @param moduleObject Instace of the module
     */
    public void setModuleObject(Object moduleObject) {
        this.moduleObject = moduleObject;
    }

    /**
     * Sets retryMax
     * 
     * @param value Value to set
     */
    public void setRetryMax(int value) {
        this.retryMax = value;
    }

    /**
     * Sets region
     * 
     * @param value Value to set
     */
    public void setRegion(Object value) {
        this.region = value;
    }

    /**
     * Sets textCase
     * 
     * @param value Value to set
     */
    public void setTextCase(Object value) {
        this.textCase = value;
    }

    /**
     * Sets date
     * 
     * @param value Value to set
     */
    public void setDate(Object value) {
        this.date = value;
    }

    /**
     * Sets city
     * 
     * @param value Value to set
     */
    public void setCity(Object value) {
        this.city = value;
    }

    /**
     * Sets country
     * 
     * @param value Value to set
     */
    public void setCountry(Object value) {
        this.country = value;
    }

    /**
     * Sets taxability
     * 
     * @param value Value to set
     */
    public void setTaxability(Object value) {
        this.taxability = value;
    }

    /**
     * Sets postalCode
     * 
     * @param value Value to set
     */
    public void setPostalCode(Object value) {
        this.postalCode = value;
    }

    /**
     * Sets addressCode
     * 
     * @param value Value to set
     */
    public void setAddressCode(Object value) {
        this.addressCode = value;
    }

    /**
     * Sets longitude
     * 
     * @param value Value to set
     */
    public void setLongitude(Object value) {
        this.longitude = value;
    }

    /**
     * Sets latitude
     * 
     * @param value Value to set
     */
    public void setLatitude(Object value) {
        this.latitude = value;
    }

    /**
     * Sets line1
     * 
     * @param value Value to set
     */
    public void setLine1(Object value) {
        this.line1 = value;
    }

    /**
     * Sets taxRegionId
     * 
     * @param value Value to set
     */
    public void setTaxRegionId(Object value) {
        this.taxRegionId = value;
    }

    /**
     * Sets line3
     * 
     * @param value Value to set
     */
    public void setLine3(Object value) {
        this.line3 = value;
    }

    /**
     * Sets coordinates
     * 
     * @param value Value to set
     */
    public void setCoordinates(Object value) {
        this.coordinates = value;
    }

    /**
     * Sets line2
     * 
     * @param value Value to set
     */
    public void setLine2(Object value) {
        this.line2 = value;
    }

    /**
     * Get all superclasses and interfaces recursively.
     * 
     * @param classes List of classes to which to add all found super classes and interfaces.
     * @param clazz   The class to start the search with.
     */
    private void computeClassHierarchy(Class clazz, List classes) {
        for (Class current = clazz; (current!= null); current = current.getSuperclass()) {
            if (classes.contains(current)) {
                return ;
            }
            classes.add(current);
            for (Class currentInterface: current.getInterfaces()) {
                computeClassHierarchy(currentInterface, classes);
            }
        }
    }

    /**
     * Checks whether the specified class parameter is an instance of {@link List }
     * 
     * @param clazz <code>Class</code> to check.
     * @return
     */
    private boolean isListClass(Class clazz) {
        List<Class> classes = new ArrayList<Class>();
        computeClassHierarchy(clazz, classes);
        return classes.contains(List.class);
    }

    /**
     * Checks whether the specified class parameter is an instance of {@link Map }
     * 
     * @param clazz <code>Class</code> to check.
     * @return
     */
    private boolean isMapClass(Class clazz) {
        List<Class> classes = new ArrayList<Class>();
        computeClassHierarchy(clazz, classes);
        return classes.contains(Map.class);
    }

    private boolean isList(Type type) {
        if ((type instanceof Class)&&isListClass(((Class) type))) {
            return true;
        }
        if (type instanceof ParameterizedType) {
            return isList(((ParameterizedType) type).getRawType());
        }
        if (type instanceof WildcardType) {
            Type[] upperBounds = ((WildcardType) type).getUpperBounds();
            return ((upperBounds.length!= 0)&&isList(upperBounds[ 0 ]));
        }
        return false;
    }

    private boolean isMap(Type type) {
        if ((type instanceof Class)&&isMapClass(((Class) type))) {
            return true;
        }
        if (type instanceof ParameterizedType) {
            return isMap(((ParameterizedType) type).getRawType());
        }
        if (type instanceof WildcardType) {
            Type[] upperBounds = ((WildcardType) type).getUpperBounds();
            return ((upperBounds.length!= 0)&&isMap(upperBounds[ 0 ]));
        }
        return false;
    }

    private boolean isAssignableFrom(Type expectedType, Class clazz) {
        if (expectedType instanceof Class) {
            return ((Class) expectedType).isAssignableFrom(clazz);
        }
        if (expectedType instanceof ParameterizedType) {
            return isAssignableFrom(((ParameterizedType) expectedType).getRawType(), clazz);
        }
        if (expectedType instanceof WildcardType) {
            Type[] upperBounds = ((WildcardType) expectedType).getUpperBounds();
            if (upperBounds.length!= 0) {
                return isAssignableFrom(upperBounds[ 0 ], clazz);
            }
        }
        return false;
    }

    private Object evaluate(MuleMessage muleMessage, Object source) {
        if (source instanceof String) {
            String stringSource = ((String) source);
            if (stringSource.startsWith(patternInfo.getPrefix())&&stringSource.endsWith(patternInfo.getSuffix())) {
                return expressionManager.evaluate(stringSource, muleMessage);
            } else {
                return expressionManager.parse(stringSource, muleMessage);
            }
        }
        return source;
    }

    private Object evaluateAndTransform(MuleMessage muleMessage, Type expectedType, Object source)
        throws TransformerException
    {
        if (source == null) {
            return source;
        }
        Object target = null;
        if (isList(source.getClass())) {
            if (isList(expectedType)) {
                List newList = new ArrayList();
                Type valueType = ((ParameterizedType) expectedType).getActualTypeArguments()[ 0 ];
                ListIterator iterator = ((List) source).listIterator();
                while (iterator.hasNext()) {
                    Object subTarget = iterator.next();
                    newList.add(evaluateAndTransform(muleMessage, valueType, subTarget));
                }
                target = newList;
            } else {
                target = source;
            }
        } else {
            if (isMap(source.getClass())) {
                if (isMap(expectedType)) {
                    Type keyType = Object.class;
                    Type valueType = Object.class;
                    if (expectedType instanceof ParameterizedType) {
                        keyType = ((ParameterizedType) expectedType).getActualTypeArguments()[ 0 ];
                        valueType = ((ParameterizedType) expectedType).getActualTypeArguments()[ 1 ];
                    }
                    Map map = ((Map) source);
                    Map newMap = new HashMap();
                    for (Object entryObj: map.entrySet()) {
                        {
                            Map.Entry entry = ((Map.Entry) entryObj);
                            Object newKey = evaluateAndTransform(muleMessage, keyType, entry.getKey());
                            Object newValue = evaluateAndTransform(muleMessage, valueType, entry.getValue());
                            newMap.put(newKey, newValue);
                        }
                    }
                    target = newMap;
                } else {
                    target = source;
                }
            } else {
                target = evaluate(muleMessage, source);
            }
        }
        if ((target!= null)&&(!isAssignableFrom(expectedType, target.getClass()))) {
            DataType sourceDataType = DataTypeFactory.create(target.getClass());
            DataType targetDataType = DataTypeFactory.create(((Class) expectedType));
            Transformer t = muleContext.getRegistry().lookupTransformer(sourceDataType, targetDataType);
            return t.transform(target);
        } else {
            return target;
        }
    }

    /**
     * Invokes the MessageProcessor.
     * 
     * @param event MuleEvent to be processed
     * @throws MuleException
     */
    public MuleEvent process(MuleEvent event)
        throws MuleException
    {
        MuleMessage muleMessage = event.getMessage();
        AvalaraModuleLifecycleAdapter castedModuleObject = null;
        if (moduleObject instanceof String) {
            castedModuleObject = ((AvalaraModuleLifecycleAdapter) muleContext.getRegistry().lookupObject(((String) moduleObject)));
            if (castedModuleObject == null) {
                throw new MessagingException(CoreMessages.failedToCreate("validateAddress"), event, new RuntimeException("Cannot find the configuration specified by the config-ref attribute."));
            }
        } else {
            castedModuleObject = ((AvalaraModuleLifecycleAdapter) moduleObject);
        }
        try {
            String transformedLine1 = ((String) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_line1Type").getGenericType(), line1));
            String transformedLine2 = ((String) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_line2Type").getGenericType(), line2));
            String transformedLine3 = ((String) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_line3Type").getGenericType(), line3));
            String transformedCity = ((String) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_cityType").getGenericType(), city));
            String transformedRegion = ((String) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_regionType").getGenericType(), region));
            String transformedCountry = ((String) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_countryType").getGenericType(), country));
            String transformedPostalCode = ((String) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_postalCodeType").getGenericType(), postalCode));
            String transformedAddressCode = ((String) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_addressCodeType").getGenericType(), addressCode));
            Integer transformedTaxRegionId = ((Integer) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_taxRegionIdType").getGenericType(), taxRegionId));
            String transformedLatitude = ((String) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_latitudeType").getGenericType(), latitude));
            String transformedLongitude = ((String) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_longitudeType").getGenericType(), longitude));
            TextCaseType transformedTextCase = ((TextCaseType) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_textCaseType").getGenericType(), textCase));
            Boolean transformedCoordinates = ((Boolean) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_coordinatesType").getGenericType(), coordinates));
            Boolean transformedTaxability = ((Boolean) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_taxabilityType").getGenericType(), taxability));
            Date transformedDate = ((Date) evaluateAndTransform(muleMessage, ValidateAddressMessageProcessor.class.getDeclaredField("_dateType").getGenericType(), date));
            retryCount.getAndIncrement();
            Object resultPayload;
            resultPayload = castedModuleObject.validateAddress(transformedLine1, transformedLine2, transformedLine3, transformedCity, transformedRegion, transformedCountry, transformedPostalCode, transformedAddressCode, transformedTaxRegionId, transformedLatitude, transformedLongitude, transformedTextCase, transformedCoordinates, transformedTaxability, transformedDate);
            if (resultPayload == null) {
                event = new DefaultMuleEvent(new DefaultMuleMessage(NullPayload.getInstance(), muleContext), event);
            } else {
                List<Transformer> transformerList;
                transformerList = new ArrayList<Transformer>();
                transformerList.add(new TransformerTemplate(new TransformerTemplate.OverwitePayloadCallback(resultPayload)));
                event.getMessage().applyTransformers(event, transformerList);
            }
            retryCount.set(0);
            return event;
        } catch (Exception e) {
            throw new MessagingException(CoreMessages.failedToInvoke("validateAddress"), event, e);
        }
    }

}
