
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.CreateOrderInvoiceMessageProcessor;
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 CreateOrderInvoiceDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(CreateOrderInvoiceMessageProcessor.class.getName());
        String configRef = element.getAttribute("config-ref");
        if ((configRef!= null)&&(!StringUtils.isBlank(configRef))) {
            builder.addPropertyValue("moduleObject", configRef);
        }
        if ((element.getAttribute("orderId")!= null)&&(!StringUtils.isBlank(element.getAttribute("orderId")))) {
            builder.addPropertyValue("orderId", element.getAttribute("orderId"));
        }
        Element itemsQuantitiesListElement = null;
        itemsQuantitiesListElement = DomUtils.getChildElementByTagName(element, "items-quantities");
        List<Element> itemsQuantitiesMapChilds = null;
        if (itemsQuantitiesListElement!= null) {
            String itemsQuantitiesRef = itemsQuantitiesListElement.getAttribute("ref");
            if ((itemsQuantitiesRef!= null)&&(!StringUtils.isBlank(itemsQuantitiesRef))) {
                if ((!itemsQuantitiesRef.startsWith(patternInfo.getPrefix()))&&(!itemsQuantitiesRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("itemsQuantities", new RuntimeBeanReference(itemsQuantitiesRef));
                } else {
                    builder.addPropertyValue("itemsQuantities", itemsQuantitiesRef);
                }
            } else {
                ManagedMap itemsQuantities = new ManagedMap();
                itemsQuantitiesMapChilds = DomUtils.getChildElementsByTagName(itemsQuantitiesListElement, "items-quantity");
                if (itemsQuantitiesMapChilds!= null) {
                    if (itemsQuantitiesMapChilds.size() == 0) {
                        itemsQuantitiesMapChilds = DomUtils.getChildElements(itemsQuantitiesListElement);
                    }
                    for (Element itemsQuantitiesChild: itemsQuantitiesMapChilds) {
                        String itemsQuantitiesValueRef = itemsQuantitiesChild.getAttribute("value-ref");
                        String itemsQuantitiesKeyRef = itemsQuantitiesChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((itemsQuantitiesValueRef!= null)&&(!StringUtils.isBlank(itemsQuantitiesValueRef))) {
                            if ((!itemsQuantitiesValueRef.startsWith(patternInfo.getPrefix()))&&(!itemsQuantitiesValueRef.endsWith(patternInfo.getSuffix()))) {
                                valueObject = new RuntimeBeanReference(itemsQuantitiesValueRef);
                            } else {
                                valueObject = itemsQuantitiesValueRef;
                            }
                        } else {
                            valueObject = itemsQuantitiesChild.getTextContent();
                        }
                        if ((itemsQuantitiesKeyRef!= null)&&(!StringUtils.isBlank(itemsQuantitiesKeyRef))) {
                            keyObject = new RuntimeBeanReference(itemsQuantitiesKeyRef);
                        } else {
                            keyObject = itemsQuantitiesChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = itemsQuantitiesChild.getTagName();
                        }
                        itemsQuantities.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("itemsQuantities", itemsQuantities);
            }
        }
        if ((element.getAttribute("comment")!= null)&&(!StringUtils.isBlank(element.getAttribute("comment")))) {
            builder.addPropertyValue("comment", element.getAttribute("comment"));
        }
        if ((element.getAttribute("sendEmail")!= null)&&(!StringUtils.isBlank(element.getAttribute("sendEmail")))) {
            builder.addPropertyValue("sendEmail", element.getAttribute("sendEmail"));
        }
        if ((element.getAttribute("includeCommentInEmail")!= null)&&(!StringUtils.isBlank(element.getAttribute("includeCommentInEmail")))) {
            builder.addPropertyValue("includeCommentInEmail", element.getAttribute("includeCommentInEmail"));
        }
        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;
        }
    }

}
