
package org.mule.modules.quickbooks.windows.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.quickbooks.windows.config.UpdateMessageProcessor;
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 UpdateDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(UpdateMessageProcessor.class.getName());
        String configRef = element.getAttribute("config-ref");
        if ((configRef!= null)&&(!StringUtils.isBlank(configRef))) {
            builder.addPropertyValue("moduleObject", configRef);
        }
        if ((element.getAttribute("realmId")!= null)&&(!StringUtils.isBlank(element.getAttribute("realmId")))) {
            builder.addPropertyValue("realmId", element.getAttribute("realmId"));
        }
        if ((element.getAttribute("appKey")!= null)&&(!StringUtils.isBlank(element.getAttribute("appKey")))) {
            builder.addPropertyValue("appKey", element.getAttribute("appKey"));
        }
        if ((element.getAttribute("realmIdPseudonym")!= null)&&(!StringUtils.isBlank(element.getAttribute("realmIdPseudonym")))) {
            builder.addPropertyValue("realmIdPseudonym", element.getAttribute("realmIdPseudonym"));
        }
        if ((element.getAttribute("authIdPseudonym")!= null)&&(!StringUtils.isBlank(element.getAttribute("authIdPseudonym")))) {
            builder.addPropertyValue("authIdPseudonym", element.getAttribute("authIdPseudonym"));
        }
        if (element.hasAttribute("type")) {
            builder.addPropertyValue("type", element.getAttribute("type"));
        }
        Element objListElement = null;
        objListElement = DomUtils.getChildElementByTagName(element, "obj");
        List<Element> objListChilds = null;
        if (objListElement!= null) {
            String objRef = objListElement.getAttribute("ref");
            if ((objRef!= null)&&(!StringUtils.isBlank(objRef))) {
                if ((!objRef.startsWith(patternInfo.getPrefix()))&&(!objRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("obj", new RuntimeBeanReference(objRef));
                } else {
                    builder.addPropertyValue("obj", objRef);
                }
            } else {
                ManagedMap obj = new ManagedMap();
                objListChilds = DomUtils.getChildElementsByTagName(objListElement, "obj");
                if (objListChilds!= null) {
                    if (objListChilds.size() == 0) {
                        objListChilds = DomUtils.getChildElements(objListElement);
                    }
                    for (Element objChild: objListChilds) {
                        String objValueRef = objChild.getAttribute("value-ref");
                        String objKeyRef = objChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((objValueRef!= null)&&(!StringUtils.isBlank(objValueRef))) {
                            valueObject = new RuntimeBeanReference(objValueRef);
                        } else {
                            valueObject = objChild.getTextContent();
                        }
                        if ((objKeyRef!= null)&&(!StringUtils.isBlank(objKeyRef))) {
                            keyObject = new RuntimeBeanReference(objKeyRef);
                        } else {
                            keyObject = objChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = objChild.getTagName();
                        }
                        obj.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("obj", obj);
            }
        }
        if ((element.getAttribute("requestId")!= null)&&(!StringUtils.isBlank(element.getAttribute("requestId")))) {
            builder.addPropertyValue("requestId", element.getAttribute("requestId"));
        }
        if ((element.getAttribute("draft")!= null)&&(!StringUtils.isBlank(element.getAttribute("draft")))) {
            builder.addPropertyValue("draft", element.getAttribute("draft"));
        }
        if ((element.getAttribute("fullResponse")!= null)&&(!StringUtils.isBlank(element.getAttribute("fullResponse")))) {
            builder.addPropertyValue("fullResponse", element.getAttribute("fullResponse"));
        }
        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;
        }
    }

}
