
package org.mule.modules.quickbooks.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.config.CreateAccountMessageProcessor;
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 CreateAccountDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(CreateAccountMessageProcessor.class.getName());
        String configRef = element.getAttribute("config-ref");
        if ((configRef!= null)&&(!StringUtils.isBlank(configRef))) {
            builder.addPropertyValue("moduleObject", configRef);
        }
        if ((element.getAttribute("accessToken")!= null)&&(!StringUtils.isBlank(element.getAttribute("accessToken")))) {
            builder.addPropertyValue("accessToken", element.getAttribute("accessToken"));
        }
        if ((element.getAttribute("accessTokenSecret")!= null)&&(!StringUtils.isBlank(element.getAttribute("accessTokenSecret")))) {
            builder.addPropertyValue("accessTokenSecret", element.getAttribute("accessTokenSecret"));
        }
        if ((element.getAttribute("name")!= null)&&(!StringUtils.isBlank(element.getAttribute("name")))) {
            builder.addPropertyValue("name", element.getAttribute("name"));
        }
        if ((element.getAttribute("desc")!= null)&&(!StringUtils.isBlank(element.getAttribute("desc")))) {
            builder.addPropertyValue("desc", element.getAttribute("desc"));
        }
        if (element.hasAttribute("subtype")) {
            builder.addPropertyValue("subtype", element.getAttribute("subtype"));
        }
        if ((element.getAttribute("acctNum")!= null)&&(!StringUtils.isBlank(element.getAttribute("acctNum")))) {
            builder.addPropertyValue("acctNum", element.getAttribute("acctNum"));
        }
        if ((element.getAttribute("openingBalance")!= null)&&(!StringUtils.isBlank(element.getAttribute("openingBalance")))) {
            builder.addPropertyValue("openingBalance", element.getAttribute("openingBalance"));
        }
        if ((element.getAttribute("openingBalanceDate")!= null)&&(!StringUtils.isBlank(element.getAttribute("openingBalanceDate")))) {
            builder.addPropertyValue("openingBalanceDate", element.getAttribute("openingBalanceDate"));
        }
        Element accountParentIdListElement = null;
        accountParentIdListElement = DomUtils.getChildElementByTagName(element, "account-parent-id");
        List<Element> accountParentIdListChilds = null;
        if (accountParentIdListElement!= null) {
            String accountParentIdRef = accountParentIdListElement.getAttribute("ref");
            if ((accountParentIdRef!= null)&&(!StringUtils.isBlank(accountParentIdRef))) {
                if ((!accountParentIdRef.startsWith(patternInfo.getPrefix()))&&(!accountParentIdRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("accountParentId", new RuntimeBeanReference(accountParentIdRef));
                } else {
                    builder.addPropertyValue("accountParentId", accountParentIdRef);
                }
            } else {
                ManagedMap accountParentId = new ManagedMap();
                accountParentIdListChilds = DomUtils.getChildElementsByTagName(accountParentIdListElement, "account-parent-id");
                if (accountParentIdListChilds!= null) {
                    if (accountParentIdListChilds.size() == 0) {
                        accountParentIdListChilds = DomUtils.getChildElements(accountParentIdListElement);
                    }
                    for (Element accountParentIdChild: accountParentIdListChilds) {
                        String accountParentIdValueRef = accountParentIdChild.getAttribute("value-ref");
                        String accountParentIdKeyRef = accountParentIdChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((accountParentIdValueRef!= null)&&(!StringUtils.isBlank(accountParentIdValueRef))) {
                            valueObject = new RuntimeBeanReference(accountParentIdValueRef);
                        } else {
                            valueObject = accountParentIdChild.getTextContent();
                        }
                        if ((accountParentIdKeyRef!= null)&&(!StringUtils.isBlank(accountParentIdKeyRef))) {
                            keyObject = new RuntimeBeanReference(accountParentIdKeyRef);
                        } else {
                            keyObject = accountParentIdChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = accountParentIdChild.getTagName();
                        }
                        accountParentId.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("accountParentId", accountParentId);
            }
        }
        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;
        }
    }

}
