
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.CreateItemMessageProcessor;
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 CreateItemDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(CreateItemMessageProcessor.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"));
        }
        Element unitPriceListElement = null;
        unitPriceListElement = DomUtils.getChildElementByTagName(element, "unit-price");
        List<Element> unitPriceListChilds = null;
        if (unitPriceListElement!= null) {
            String unitPriceRef = unitPriceListElement.getAttribute("ref");
            if ((unitPriceRef!= null)&&(!StringUtils.isBlank(unitPriceRef))) {
                if ((!unitPriceRef.startsWith(patternInfo.getPrefix()))&&(!unitPriceRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("unitPrice", new RuntimeBeanReference(unitPriceRef));
                } else {
                    builder.addPropertyValue("unitPrice", unitPriceRef);
                }
            } else {
                ManagedMap unitPrice = new ManagedMap();
                unitPriceListChilds = DomUtils.getChildElementsByTagName(unitPriceListElement, "unit-price");
                if (unitPriceListChilds!= null) {
                    if (unitPriceListChilds.size() == 0) {
                        unitPriceListChilds = DomUtils.getChildElements(unitPriceListElement);
                    }
                    for (Element unitPriceChild: unitPriceListChilds) {
                        String unitPriceValueRef = unitPriceChild.getAttribute("value-ref");
                        String unitPriceKeyRef = unitPriceChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((unitPriceValueRef!= null)&&(!StringUtils.isBlank(unitPriceValueRef))) {
                            valueObject = new RuntimeBeanReference(unitPriceValueRef);
                        } else {
                            valueObject = unitPriceChild.getTextContent();
                        }
                        if ((unitPriceKeyRef!= null)&&(!StringUtils.isBlank(unitPriceKeyRef))) {
                            keyObject = new RuntimeBeanReference(unitPriceKeyRef);
                        } else {
                            keyObject = unitPriceChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = unitPriceChild.getTagName();
                        }
                        unitPrice.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("unitPrice", unitPrice);
            }
        }
        if ((element.getAttribute("desc")!= null)&&(!StringUtils.isBlank(element.getAttribute("desc")))) {
            builder.addPropertyValue("desc", element.getAttribute("desc"));
        }
        if ((element.getAttribute("taxable")!= null)&&(!StringUtils.isBlank(element.getAttribute("taxable")))) {
            builder.addPropertyValue("taxable", element.getAttribute("taxable"));
        }
        Element incomeAccountListElement = null;
        incomeAccountListElement = DomUtils.getChildElementByTagName(element, "income-account");
        List<Element> incomeAccountListChilds = null;
        if (incomeAccountListElement!= null) {
            String incomeAccountRef = incomeAccountListElement.getAttribute("ref");
            if ((incomeAccountRef!= null)&&(!StringUtils.isBlank(incomeAccountRef))) {
                if ((!incomeAccountRef.startsWith(patternInfo.getPrefix()))&&(!incomeAccountRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("incomeAccount", new RuntimeBeanReference(incomeAccountRef));
                } else {
                    builder.addPropertyValue("incomeAccount", incomeAccountRef);
                }
            } else {
                ManagedMap incomeAccount = new ManagedMap();
                incomeAccountListChilds = DomUtils.getChildElementsByTagName(incomeAccountListElement, "income-account");
                if (incomeAccountListChilds!= null) {
                    if (incomeAccountListChilds.size() == 0) {
                        incomeAccountListChilds = DomUtils.getChildElements(incomeAccountListElement);
                    }
                    for (Element incomeAccountChild: incomeAccountListChilds) {
                        String incomeAccountValueRef = incomeAccountChild.getAttribute("value-ref");
                        String incomeAccountKeyRef = incomeAccountChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((incomeAccountValueRef!= null)&&(!StringUtils.isBlank(incomeAccountValueRef))) {
                            valueObject = new RuntimeBeanReference(incomeAccountValueRef);
                        } else {
                            valueObject = incomeAccountChild.getTextContent();
                        }
                        if ((incomeAccountKeyRef!= null)&&(!StringUtils.isBlank(incomeAccountKeyRef))) {
                            keyObject = new RuntimeBeanReference(incomeAccountKeyRef);
                        } else {
                            keyObject = incomeAccountChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = incomeAccountChild.getTagName();
                        }
                        incomeAccount.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("incomeAccount", incomeAccount);
            }
        }
        Element itemParentIdListElement = null;
        itemParentIdListElement = DomUtils.getChildElementByTagName(element, "item-parent-id");
        List<Element> itemParentIdListChilds = null;
        if (itemParentIdListElement!= null) {
            String itemParentIdRef = itemParentIdListElement.getAttribute("ref");
            if ((itemParentIdRef!= null)&&(!StringUtils.isBlank(itemParentIdRef))) {
                if ((!itemParentIdRef.startsWith(patternInfo.getPrefix()))&&(!itemParentIdRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("itemParentId", new RuntimeBeanReference(itemParentIdRef));
                } else {
                    builder.addPropertyValue("itemParentId", itemParentIdRef);
                }
            } else {
                ManagedMap itemParentId = new ManagedMap();
                itemParentIdListChilds = DomUtils.getChildElementsByTagName(itemParentIdListElement, "item-parent-id");
                if (itemParentIdListChilds!= null) {
                    if (itemParentIdListChilds.size() == 0) {
                        itemParentIdListChilds = DomUtils.getChildElements(itemParentIdListElement);
                    }
                    for (Element itemParentIdChild: itemParentIdListChilds) {
                        String itemParentIdValueRef = itemParentIdChild.getAttribute("value-ref");
                        String itemParentIdKeyRef = itemParentIdChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((itemParentIdValueRef!= null)&&(!StringUtils.isBlank(itemParentIdValueRef))) {
                            valueObject = new RuntimeBeanReference(itemParentIdValueRef);
                        } else {
                            valueObject = itemParentIdChild.getTextContent();
                        }
                        if ((itemParentIdKeyRef!= null)&&(!StringUtils.isBlank(itemParentIdKeyRef))) {
                            keyObject = new RuntimeBeanReference(itemParentIdKeyRef);
                        } else {
                            keyObject = itemParentIdChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = itemParentIdChild.getTagName();
                        }
                        itemParentId.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("itemParentId", itemParentId);
            }
        }
        if ((element.getAttribute("itemParentName")!= null)&&(!StringUtils.isBlank(element.getAttribute("itemParentName")))) {
            builder.addPropertyValue("itemParentName", element.getAttribute("itemParentName"));
        }
        if ((element.getAttribute("purchaseDesc")!= null)&&(!StringUtils.isBlank(element.getAttribute("purchaseDesc")))) {
            builder.addPropertyValue("purchaseDesc", element.getAttribute("purchaseDesc"));
        }
        Element purchaseCostListElement = null;
        purchaseCostListElement = DomUtils.getChildElementByTagName(element, "purchase-cost");
        List<Element> purchaseCostListChilds = null;
        if (purchaseCostListElement!= null) {
            String purchaseCostRef = purchaseCostListElement.getAttribute("ref");
            if ((purchaseCostRef!= null)&&(!StringUtils.isBlank(purchaseCostRef))) {
                if ((!purchaseCostRef.startsWith(patternInfo.getPrefix()))&&(!purchaseCostRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("purchaseCost", new RuntimeBeanReference(purchaseCostRef));
                } else {
                    builder.addPropertyValue("purchaseCost", purchaseCostRef);
                }
            } else {
                ManagedMap purchaseCost = new ManagedMap();
                purchaseCostListChilds = DomUtils.getChildElementsByTagName(purchaseCostListElement, "purchase-cost");
                if (purchaseCostListChilds!= null) {
                    if (purchaseCostListChilds.size() == 0) {
                        purchaseCostListChilds = DomUtils.getChildElements(purchaseCostListElement);
                    }
                    for (Element purchaseCostChild: purchaseCostListChilds) {
                        String purchaseCostValueRef = purchaseCostChild.getAttribute("value-ref");
                        String purchaseCostKeyRef = purchaseCostChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((purchaseCostValueRef!= null)&&(!StringUtils.isBlank(purchaseCostValueRef))) {
                            valueObject = new RuntimeBeanReference(purchaseCostValueRef);
                        } else {
                            valueObject = purchaseCostChild.getTextContent();
                        }
                        if ((purchaseCostKeyRef!= null)&&(!StringUtils.isBlank(purchaseCostKeyRef))) {
                            keyObject = new RuntimeBeanReference(purchaseCostKeyRef);
                        } else {
                            keyObject = purchaseCostChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = purchaseCostChild.getTagName();
                        }
                        purchaseCost.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("purchaseCost", purchaseCost);
            }
        }
        Element expenseAccountListElement = null;
        expenseAccountListElement = DomUtils.getChildElementByTagName(element, "expense-account");
        List<Element> expenseAccountListChilds = null;
        if (expenseAccountListElement!= null) {
            String expenseAccountRef = expenseAccountListElement.getAttribute("ref");
            if ((expenseAccountRef!= null)&&(!StringUtils.isBlank(expenseAccountRef))) {
                if ((!expenseAccountRef.startsWith(patternInfo.getPrefix()))&&(!expenseAccountRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("expenseAccount", new RuntimeBeanReference(expenseAccountRef));
                } else {
                    builder.addPropertyValue("expenseAccount", expenseAccountRef);
                }
            } else {
                ManagedMap expenseAccount = new ManagedMap();
                expenseAccountListChilds = DomUtils.getChildElementsByTagName(expenseAccountListElement, "expense-account");
                if (expenseAccountListChilds!= null) {
                    if (expenseAccountListChilds.size() == 0) {
                        expenseAccountListChilds = DomUtils.getChildElements(expenseAccountListElement);
                    }
                    for (Element expenseAccountChild: expenseAccountListChilds) {
                        String expenseAccountValueRef = expenseAccountChild.getAttribute("value-ref");
                        String expenseAccountKeyRef = expenseAccountChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((expenseAccountValueRef!= null)&&(!StringUtils.isBlank(expenseAccountValueRef))) {
                            valueObject = new RuntimeBeanReference(expenseAccountValueRef);
                        } else {
                            valueObject = expenseAccountChild.getTextContent();
                        }
                        if ((expenseAccountKeyRef!= null)&&(!StringUtils.isBlank(expenseAccountKeyRef))) {
                            keyObject = new RuntimeBeanReference(expenseAccountKeyRef);
                        } else {
                            keyObject = expenseAccountChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = expenseAccountChild.getTagName();
                        }
                        expenseAccount.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("expenseAccount", expenseAccount);
            }
        }
        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;
        }
    }

}
