
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.CreateCheckMessageProcessor;
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 CreateCheckDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(CreateCheckMessageProcessor.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"));
        }
        Element headerListElement = null;
        headerListElement = DomUtils.getChildElementByTagName(element, "header");
        List<Element> headerListChilds = null;
        if (headerListElement!= null) {
            String headerRef = headerListElement.getAttribute("ref");
            if ((headerRef!= null)&&(!StringUtils.isBlank(headerRef))) {
                if ((!headerRef.startsWith(patternInfo.getPrefix()))&&(!headerRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("header", new RuntimeBeanReference(headerRef));
                } else {
                    builder.addPropertyValue("header", headerRef);
                }
            } else {
                ManagedMap header = new ManagedMap();
                headerListChilds = DomUtils.getChildElementsByTagName(headerListElement, "header");
                if (headerListChilds!= null) {
                    if (headerListChilds.size() == 0) {
                        headerListChilds = DomUtils.getChildElements(headerListElement);
                    }
                    for (Element headerChild: headerListChilds) {
                        String headerValueRef = headerChild.getAttribute("value-ref");
                        String headerKeyRef = headerChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((headerValueRef!= null)&&(!StringUtils.isBlank(headerValueRef))) {
                            valueObject = new RuntimeBeanReference(headerValueRef);
                        } else {
                            valueObject = headerChild.getTextContent();
                        }
                        if ((headerKeyRef!= null)&&(!StringUtils.isBlank(headerKeyRef))) {
                            keyObject = new RuntimeBeanReference(headerKeyRef);
                        } else {
                            keyObject = headerChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = headerChild.getTagName();
                        }
                        header.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("header", header);
            }
        }
        Element lineListElement = null;
        lineListElement = DomUtils.getChildElementByTagName(element, "line");
        List<Element> lineListChilds = null;
        if (lineListElement!= null) {
            String lineRef = lineListElement.getAttribute("ref");
            if ((lineRef!= null)&&(!StringUtils.isBlank(lineRef))) {
                if ((!lineRef.startsWith(patternInfo.getPrefix()))&&(!lineRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("line", new RuntimeBeanReference(lineRef));
                } else {
                    builder.addPropertyValue("line", lineRef);
                }
            } else {
                ManagedList line = new ManagedList();
                lineListChilds = DomUtils.getChildElementsByTagName(lineListElement, "line");
                if (lineListChilds!= null) {
                    for (Element lineChild: lineListChilds) {
                        String valueRef = lineChild.getAttribute("value-ref");
                        if ((valueRef!= null)&&(!StringUtils.isBlank(valueRef))) {
                            line.add(new RuntimeBeanReference(valueRef));
                        } else {
                            List<Element> innerlineListChilds = null;
                            if (lineChild!= null) {
                                String innerlineRef = lineChild.getAttribute("ref");
                                if ((innerlineRef!= null)&&(!StringUtils.isBlank(innerlineRef))) {
                                    if ((!innerlineRef.startsWith(patternInfo.getPrefix()))&&(!innerlineRef.endsWith(patternInfo.getSuffix()))) {
                                        builder.addPropertyValue("inner-line", new RuntimeBeanReference(innerlineRef));
                                    } else {
                                        builder.addPropertyValue("inner-line", innerlineRef);
                                    }
                                } else {
                                    ManagedMap innerline = new ManagedMap();
                                    innerlineListChilds = DomUtils.getChildElementsByTagName(lineChild, "inner-line");
                                    if (innerlineListChilds!= null) {
                                        if (innerlineListChilds.size() == 0) {
                                            innerlineListChilds = DomUtils.getChildElements(lineChild);
                                        }
                                        for (Element innerlineChild: innerlineListChilds) {
                                            String innerlineValueRef = innerlineChild.getAttribute("value-ref");
                                            String innerlineKeyRef = innerlineChild.getAttribute("key-ref");
                                            Object valueObject = null;
                                            Object keyObject = null;
                                            if ((innerlineValueRef!= null)&&(!StringUtils.isBlank(innerlineValueRef))) {
                                                valueObject = new RuntimeBeanReference(innerlineValueRef);
                                            } else {
                                                valueObject = innerlineChild.getTextContent();
                                            }
                                            if ((innerlineKeyRef!= null)&&(!StringUtils.isBlank(innerlineKeyRef))) {
                                                keyObject = new RuntimeBeanReference(innerlineKeyRef);
                                            } else {
                                                keyObject = innerlineChild.getAttribute("key");
                                            }
                                            if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                                                keyObject = innerlineChild.getTagName();
                                            }
                                            innerline.put(keyObject, valueObject);
                                        }
                                    }
                                    line.add(innerline);
                                }
                            }
                        }
                    }
                }
                builder.addPropertyValue("line", line);
            }
        }
        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;
        }
    }

}
