
package org.mule.modules.avalara.config.spring;

import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.mule.config.spring.MuleHierarchicalBeanDefinitionParserDelegate;
import org.mule.config.spring.util.SpringXMLUtils;
import org.mule.modules.avalara.config.GetTaxMessageProcessor;
import org.mule.util.TemplateParser;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;

public class GetTaxDefinitionParser
    implements BeanDefinitionParser
{

    /**
     * Mule Pattern Info
     * 
     */
    private TemplateParser.PatternInfo patternInfo;

    public GetTaxDefinitionParser() {
        patternInfo = TemplateParser.createMuleStyleParser().getStyle();
    }

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(GetTaxMessageProcessor.class.getName());
        String configRef = element.getAttribute("config-ref");
        if ((configRef!= null)&&(!StringUtils.isBlank(configRef))) {
            builder.addPropertyValue("moduleObject", configRef);
        }
        if ((element.getAttribute("companyCode")!= null)&&(!StringUtils.isBlank(element.getAttribute("companyCode")))) {
            builder.addPropertyValue("companyCode", element.getAttribute("companyCode"));
        }
        if (element.hasAttribute("docType")) {
            builder.addPropertyValue("docType", element.getAttribute("docType"));
        }
        if ((element.getAttribute("docCode")!= null)&&(!StringUtils.isBlank(element.getAttribute("docCode")))) {
            builder.addPropertyValue("docCode", element.getAttribute("docCode"));
        }
        if ((element.getAttribute("docDate")!= null)&&(!StringUtils.isBlank(element.getAttribute("docDate")))) {
            builder.addPropertyValue("docDate", element.getAttribute("docDate"));
        }
        if ((element.getAttribute("salespersonCode")!= null)&&(!StringUtils.isBlank(element.getAttribute("salespersonCode")))) {
            builder.addPropertyValue("salespersonCode", element.getAttribute("salespersonCode"));
        }
        if ((element.getAttribute("customerCode")!= null)&&(!StringUtils.isBlank(element.getAttribute("customerCode")))) {
            builder.addPropertyValue("customerCode", element.getAttribute("customerCode"));
        }
        if ((element.getAttribute("customerUsageType")!= null)&&(!StringUtils.isBlank(element.getAttribute("customerUsageType")))) {
            builder.addPropertyValue("customerUsageType", element.getAttribute("customerUsageType"));
        }
        if ((element.getAttribute("discount")!= null)&&(!StringUtils.isBlank(element.getAttribute("discount")))) {
            builder.addPropertyValue("discount", element.getAttribute("discount"));
        }
        if ((element.getAttribute("purchaseOrderNo")!= null)&&(!StringUtils.isBlank(element.getAttribute("purchaseOrderNo")))) {
            builder.addPropertyValue("purchaseOrderNo", element.getAttribute("purchaseOrderNo"));
        }
        if ((element.getAttribute("exemptionNo")!= null)&&(!StringUtils.isBlank(element.getAttribute("exemptionNo")))) {
            builder.addPropertyValue("exemptionNo", element.getAttribute("exemptionNo"));
        }
        if ((element.getAttribute("originCode")!= null)&&(!StringUtils.isBlank(element.getAttribute("originCode")))) {
            builder.addPropertyValue("originCode", element.getAttribute("originCode"));
        }
        if ((element.getAttribute("destinationCode")!= null)&&(!StringUtils.isBlank(element.getAttribute("destinationCode")))) {
            builder.addPropertyValue("destinationCode", element.getAttribute("destinationCode"));
        }
        Element baseAddressesListElement = null;
        baseAddressesListElement = DomUtils.getChildElementByTagName(element, "base-addresses");
        List<Element> baseAddressesListChilds = null;
        if (baseAddressesListElement!= null) {
            String baseAddressesRef = baseAddressesListElement.getAttribute("ref");
            if ((baseAddressesRef!= null)&&(!StringUtils.isBlank(baseAddressesRef))) {
                if ((!baseAddressesRef.startsWith(patternInfo.getPrefix()))&&(!baseAddressesRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("baseAddresses", new RuntimeBeanReference(baseAddressesRef));
                } else {
                    builder.addPropertyValue("baseAddresses", baseAddressesRef);
                }
            } else {
                ManagedList baseAddresses = new ManagedList();
                baseAddressesListChilds = DomUtils.getChildElementsByTagName(baseAddressesListElement, "base-address");
                if (baseAddressesListChilds!= null) {
                    for (Element baseAddressesChild: baseAddressesListChilds) {
                        String valueRef = baseAddressesChild.getAttribute("value-ref");
                        if ((valueRef!= null)&&(!StringUtils.isBlank(valueRef))) {
                            baseAddresses.add(new RuntimeBeanReference(valueRef));
                        } else {
                            List<Element> innerbaseaddressListChilds = null;
                            if (baseAddressesChild!= null) {
                                String innerbaseaddressRef = baseAddressesChild.getAttribute("ref");
                                if ((innerbaseaddressRef!= null)&&(!StringUtils.isBlank(innerbaseaddressRef))) {
                                    if ((!innerbaseaddressRef.startsWith(patternInfo.getPrefix()))&&(!innerbaseaddressRef.endsWith(patternInfo.getSuffix()))) {
                                        builder.addPropertyValue("inner-base-address", new RuntimeBeanReference(innerbaseaddressRef));
                                    } else {
                                        builder.addPropertyValue("inner-base-address", innerbaseaddressRef);
                                    }
                                } else {
                                    ManagedMap innerbaseaddress = new ManagedMap();
                                    innerbaseaddressListChilds = DomUtils.getChildElementsByTagName(baseAddressesChild, "inner-base-addres");
                                    if (innerbaseaddressListChilds!= null) {
                                        if (innerbaseaddressListChilds.size() == 0) {
                                            innerbaseaddressListChilds = DomUtils.getChildElements(baseAddressesChild);
                                        }
                                        for (Element innerbaseaddressChild: innerbaseaddressListChilds) {
                                            String innerbaseaddressValueRef = innerbaseaddressChild.getAttribute("value-ref");
                                            String innerbaseaddressKeyRef = innerbaseaddressChild.getAttribute("key-ref");
                                            Object valueObject = null;
                                            Object keyObject = null;
                                            if ((innerbaseaddressValueRef!= null)&&(!StringUtils.isBlank(innerbaseaddressValueRef))) {
                                                valueObject = new RuntimeBeanReference(innerbaseaddressValueRef);
                                            } else {
                                                valueObject = innerbaseaddressChild.getTextContent();
                                            }
                                            if ((innerbaseaddressKeyRef!= null)&&(!StringUtils.isBlank(innerbaseaddressKeyRef))) {
                                                keyObject = new RuntimeBeanReference(innerbaseaddressKeyRef);
                                            } else {
                                                keyObject = innerbaseaddressChild.getAttribute("key");
                                            }
                                            if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                                                keyObject = innerbaseaddressChild.getTagName();
                                            }
                                            innerbaseaddress.put(keyObject, valueObject);
                                        }
                                    }
                                    baseAddresses.add(innerbaseaddress);
                                }
                            }
                        }
                    }
                }
                builder.addPropertyValue("baseAddresses", baseAddresses);
            }
        }
        Element linesListElement = null;
        linesListElement = DomUtils.getChildElementByTagName(element, "lines");
        List<Element> linesListChilds = null;
        if (linesListElement!= null) {
            String linesRef = linesListElement.getAttribute("ref");
            if ((linesRef!= null)&&(!StringUtils.isBlank(linesRef))) {
                if ((!linesRef.startsWith(patternInfo.getPrefix()))&&(!linesRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("lines", new RuntimeBeanReference(linesRef));
                } else {
                    builder.addPropertyValue("lines", linesRef);
                }
            } else {
                ManagedList lines = new ManagedList();
                linesListChilds = DomUtils.getChildElementsByTagName(linesListElement, "line");
                if (linesListChilds!= null) {
                    for (Element linesChild: linesListChilds) {
                        String valueRef = linesChild.getAttribute("value-ref");
                        if ((valueRef!= null)&&(!StringUtils.isBlank(valueRef))) {
                            lines.add(new RuntimeBeanReference(valueRef));
                        } else {
                            List<Element> innerlineListChilds = null;
                            if (linesChild!= null) {
                                String innerlineRef = linesChild.getAttribute("ref");
                                if ((innerlineRef!= null)&&(!StringUtils.isBlank(innerlineRef))) {
                                    if ((!innerlineRef.startsWith(patternInfo.getPrefix()))&&(!innerlineRef.endsWith(patternInfo.getSuffix()))) {
                                        builder.addPropertyValue("inner-line", new RuntimeBeanReference(innerlineRef));
                                    } else {
                                        builder.addPropertyValue("inner-line", innerlineRef);
                                    }
                                } else {
                                    ManagedMap innerline = new ManagedMap();
                                    innerlineListChilds = DomUtils.getChildElementsByTagName(linesChild, "inner-line");
                                    if (innerlineListChilds!= null) {
                                        if (innerlineListChilds.size() == 0) {
                                            innerlineListChilds = DomUtils.getChildElements(linesChild);
                                        }
                                        for (Element innerlineChild: innerlineListChilds) {
                                            String innerlineValueRef = innerlineChild.getAttribute("value-ref");
                                            String innerlineKeyRef = innerlineChild.getAttribute("key-ref");
                                            Object valueObject = null;
                                            Object keyObject = null;
                                            if ((innerlineValueRef!= null)&&(!StringUtils.isBlank(innerlineValueRef))) {
                                                valueObject = new RuntimeBeanReference(innerlineValueRef);
                                            } else {
                                                valueObject = innerlineChild.getTextContent();
                                            }
                                            if ((innerlineKeyRef!= null)&&(!StringUtils.isBlank(innerlineKeyRef))) {
                                                keyObject = new RuntimeBeanReference(innerlineKeyRef);
                                            } else {
                                                keyObject = innerlineChild.getAttribute("key");
                                            }
                                            if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                                                keyObject = innerlineChild.getTagName();
                                            }
                                            innerline.put(keyObject, valueObject);
                                        }
                                    }
                                    lines.add(innerline);
                                }
                            }
                        }
                    }
                }
                builder.addPropertyValue("lines", lines);
            }
        }
        if (element.hasAttribute("detailLevel")) {
            builder.addPropertyValue("detailLevel", element.getAttribute("detailLevel"));
        }
        if ((element.getAttribute("referenceCode")!= null)&&(!StringUtils.isBlank(element.getAttribute("referenceCode")))) {
            builder.addPropertyValue("referenceCode", element.getAttribute("referenceCode"));
        }
        if ((element.getAttribute("locationCode")!= null)&&(!StringUtils.isBlank(element.getAttribute("locationCode")))) {
            builder.addPropertyValue("locationCode", element.getAttribute("locationCode"));
        }
        if ((element.getAttribute("commit")!= null)&&(!StringUtils.isBlank(element.getAttribute("commit")))) {
            builder.addPropertyValue("commit", element.getAttribute("commit"));
        }
        if ((element.getAttribute("batchCode")!= null)&&(!StringUtils.isBlank(element.getAttribute("batchCode")))) {
            builder.addPropertyValue("batchCode", element.getAttribute("batchCode"));
        }
        Element taxOverrideListElement = null;
        taxOverrideListElement = DomUtils.getChildElementByTagName(element, "tax-override");
        List<Element> taxOverrideListChilds = null;
        if (taxOverrideListElement!= null) {
            String taxOverrideRef = taxOverrideListElement.getAttribute("ref");
            if ((taxOverrideRef!= null)&&(!StringUtils.isBlank(taxOverrideRef))) {
                if ((!taxOverrideRef.startsWith(patternInfo.getPrefix()))&&(!taxOverrideRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("taxOverride", new RuntimeBeanReference(taxOverrideRef));
                } else {
                    builder.addPropertyValue("taxOverride", taxOverrideRef);
                }
            } else {
                ManagedMap taxOverride = new ManagedMap();
                taxOverrideListChilds = DomUtils.getChildElementsByTagName(taxOverrideListElement, "tax-override");
                if (taxOverrideListChilds!= null) {
                    if (taxOverrideListChilds.size() == 0) {
                        taxOverrideListChilds = DomUtils.getChildElements(taxOverrideListElement);
                    }
                    for (Element taxOverrideChild: taxOverrideListChilds) {
                        String taxOverrideValueRef = taxOverrideChild.getAttribute("value-ref");
                        String taxOverrideKeyRef = taxOverrideChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((taxOverrideValueRef!= null)&&(!StringUtils.isBlank(taxOverrideValueRef))) {
                            valueObject = new RuntimeBeanReference(taxOverrideValueRef);
                        } else {
                            valueObject = taxOverrideChild.getTextContent();
                        }
                        if ((taxOverrideKeyRef!= null)&&(!StringUtils.isBlank(taxOverrideKeyRef))) {
                            keyObject = new RuntimeBeanReference(taxOverrideKeyRef);
                        } else {
                            keyObject = taxOverrideChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = taxOverrideChild.getTagName();
                        }
                        taxOverride.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("taxOverride", taxOverride);
            }
        }
        if ((element.getAttribute("currencyCode")!= null)&&(!StringUtils.isBlank(element.getAttribute("currencyCode")))) {
            builder.addPropertyValue("currencyCode", element.getAttribute("currencyCode"));
        }
        if (element.hasAttribute("serviceMode")) {
            builder.addPropertyValue("serviceMode", element.getAttribute("serviceMode"));
        }
        if ((element.getAttribute("paymentDate")!= null)&&(!StringUtils.isBlank(element.getAttribute("paymentDate")))) {
            builder.addPropertyValue("paymentDate", element.getAttribute("paymentDate"));
        }
        if ((element.getAttribute("exchangeRate")!= null)&&(!StringUtils.isBlank(element.getAttribute("exchangeRate")))) {
            builder.addPropertyValue("exchangeRate", element.getAttribute("exchangeRate"));
        }
        if ((element.getAttribute("exchangeRateEffDate")!= null)&&(!StringUtils.isBlank(element.getAttribute("exchangeRateEffDate")))) {
            builder.addPropertyValue("exchangeRateEffDate", element.getAttribute("exchangeRateEffDate"));
        }
        BeanDefinition definition = builder.getBeanDefinition();
        definition.setAttribute(MuleHierarchicalBeanDefinitionParserDelegate.MULE_NO_RECURSE, Boolean.TRUE);
        MutablePropertyValues propertyValues = parserContent.getContainingBeanDefinition().getPropertyValues();
        if (parserContent.getContainingBeanDefinition().getBeanClassName().equals("org.mule.config.spring.factories.PollingMessageSourceFactoryBean")) {
            propertyValues.addPropertyValue("messageProcessor", definition);
        } else {
            PropertyValue messageProcessors = propertyValues.getPropertyValue("messageProcessors");
            if ((messageProcessors == null)||(messageProcessors.getValue() == null)) {
                propertyValues.addPropertyValue("messageProcessors", new ManagedList());
            }
            List listMessageProcessors = ((List) propertyValues.getPropertyValue("messageProcessors").getValue());
            listMessageProcessors.add(definition);
        }
        return definition;
    }

    protected String getAttributeValue(Element element, String attributeName) {
        if (!StringUtils.isEmpty(element.getAttribute(attributeName))) {
            return element.getAttribute(attributeName);
        }
        return null;
    }

    private String generateChildBeanName(Element element) {
        String id = SpringXMLUtils.getNameOrId(element);
        if (StringUtils.isBlank(id)) {
            String parentId = SpringXMLUtils.getNameOrId(((Element) element.getParentNode()));
            return ((("."+ parentId)+":")+ element.getLocalName());
        } else {
            return id;
        }
    }

}
