
package org.mule.module.magento.config;

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.module.magento.processors.SetShoppingCartCustomerAddressesMessageProcessor;
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 SetShoppingCartCustomerAddressesDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(SetShoppingCartCustomerAddressesMessageProcessor.class.getName());
        String configRef = element.getAttribute("config-ref");
        if ((configRef!= null)&&(!StringUtils.isBlank(configRef))) {
            builder.addPropertyValue("moduleObject", configRef);
        }
        if ((element.getAttribute("quoteId")!= null)&&(!StringUtils.isBlank(element.getAttribute("quoteId")))) {
            builder.addPropertyValue("quoteId", element.getAttribute("quoteId"));
        }
        Element addressesListElement = null;
        addressesListElement = DomUtils.getChildElementByTagName(element, "addresses");
        List<Element> addressesListChilds = null;
        if (addressesListElement!= null) {
            String addressesRef = addressesListElement.getAttribute("ref");
            if ((addressesRef!= null)&&(!StringUtils.isBlank(addressesRef))) {
                if ((!addressesRef.startsWith(patternInfo.getPrefix()))&&(!addressesRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("addresses", new RuntimeBeanReference(addressesRef));
                } else {
                    builder.addPropertyValue("addresses", addressesRef);
                }
            } else {
                ManagedList addresses = new ManagedList();
                addressesListChilds = DomUtils.getChildElementsByTagName(addressesListElement, "address");
                if (addressesListChilds!= null) {
                    for (Element addressesChild: addressesListChilds) {
                        String valueRef = addressesChild.getAttribute("value-ref");
                        if ((valueRef!= null)&&(!StringUtils.isBlank(valueRef))) {
                            if ((!valueRef.startsWith(patternInfo.getPrefix()))&&(!valueRef.endsWith(patternInfo.getSuffix()))) {
                                addresses.add(new RuntimeBeanReference(valueRef));
                            } else {
                                addresses.add(valueRef);
                            }
                        } else {
                            List<Element> inneraddressMapChilds = null;
                            if (addressesChild!= null) {
                                String inneraddressRef = addressesChild.getAttribute("ref");
                                if ((inneraddressRef!= null)&&(!StringUtils.isBlank(inneraddressRef))) {
                                    if ((!inneraddressRef.startsWith(patternInfo.getPrefix()))&&(!inneraddressRef.endsWith(patternInfo.getSuffix()))) {
                                        builder.addPropertyValue("inner-address", new RuntimeBeanReference(inneraddressRef));
                                    } else {
                                        builder.addPropertyValue("inner-address", inneraddressRef);
                                    }
                                } else {
                                    ManagedMap inneraddress = new ManagedMap();
                                    inneraddressMapChilds = DomUtils.getChildElementsByTagName(addressesChild, "inner-addres");
                                    if (inneraddressMapChilds!= null) {
                                        if (inneraddressMapChilds.size() == 0) {
                                            inneraddressMapChilds = DomUtils.getChildElements(addressesChild);
                                        }
                                        for (Element inneraddressChild: inneraddressMapChilds) {
                                            String inneraddressValueRef = inneraddressChild.getAttribute("value-ref");
                                            String inneraddressKeyRef = inneraddressChild.getAttribute("key-ref");
                                            Object valueObject = null;
                                            Object keyObject = null;
                                            if ((inneraddressValueRef!= null)&&(!StringUtils.isBlank(inneraddressValueRef))) {
                                                if ((!inneraddressValueRef.startsWith(patternInfo.getPrefix()))&&(!inneraddressValueRef.endsWith(patternInfo.getSuffix()))) {
                                                    valueObject = new RuntimeBeanReference(inneraddressValueRef);
                                                } else {
                                                    valueObject = inneraddressValueRef;
                                                }
                                            } else {
                                                valueObject = inneraddressChild.getTextContent();
                                            }
                                            if ((inneraddressKeyRef!= null)&&(!StringUtils.isBlank(inneraddressKeyRef))) {
                                                keyObject = new RuntimeBeanReference(inneraddressKeyRef);
                                            } else {
                                                keyObject = inneraddressChild.getAttribute("key");
                                            }
                                            if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                                                keyObject = inneraddressChild.getTagName();
                                            }
                                            inneraddress.put(keyObject, valueObject);
                                        }
                                    }
                                    addresses.add(inneraddress);
                                }
                            }
                        }
                    }
                }
                builder.addPropertyValue("addresses", addresses);
            }
        }
        if ((element.getAttribute("storeId")!= null)&&(!StringUtils.isBlank(element.getAttribute("storeId")))) {
            builder.addPropertyValue("storeId", element.getAttribute("storeId"));
        }
        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 {
            if (parserContent.getContainingBeanDefinition().getBeanClassName().equals("org.mule.enricher.MessageEnricher")) {
                propertyValues.addPropertyValue("enrichmentMessageProcessor", 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;
        }
    }

}
