
package org.mule.modules.zuora.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.modules.zuora.processors.CreateMessageProcessor;
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 CreateDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(CreateMessageProcessor.class.getName());
        String configRef = element.getAttribute("config-ref");
        if ((configRef!= null)&&(!StringUtils.isBlank(configRef))) {
            builder.addPropertyValue("moduleObject", configRef);
        }
        if (element.hasAttribute("type")) {
            builder.addPropertyValue("type", element.getAttribute("type"));
        }
        Element zobjectsListElement = null;
        zobjectsListElement = DomUtils.getChildElementByTagName(element, "zobjects");
        List<Element> zobjectsListChilds = null;
        if (zobjectsListElement!= null) {
            String zobjectsRef = zobjectsListElement.getAttribute("ref");
            if ((zobjectsRef!= null)&&(!StringUtils.isBlank(zobjectsRef))) {
                if ((!zobjectsRef.startsWith(patternInfo.getPrefix()))&&(!zobjectsRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("zobjects", new RuntimeBeanReference(zobjectsRef));
                } else {
                    builder.addPropertyValue("zobjects", zobjectsRef);
                }
            } else {
                ManagedList zobjects = new ManagedList();
                zobjectsListChilds = DomUtils.getChildElementsByTagName(zobjectsListElement, "zobject");
                if (zobjectsListChilds!= null) {
                    for (Element zobjectsChild: zobjectsListChilds) {
                        String valueRef = zobjectsChild.getAttribute("value-ref");
                        if ((valueRef!= null)&&(!StringUtils.isBlank(valueRef))) {
                            if ((!valueRef.startsWith(patternInfo.getPrefix()))&&(!valueRef.endsWith(patternInfo.getSuffix()))) {
                                zobjects.add(new RuntimeBeanReference(valueRef));
                            } else {
                                zobjects.add(valueRef);
                            }
                        } else {
                            List<Element> innerzobjectMapChilds = null;
                            if (zobjectsChild!= null) {
                                String innerzobjectRef = zobjectsChild.getAttribute("ref");
                                if ((innerzobjectRef!= null)&&(!StringUtils.isBlank(innerzobjectRef))) {
                                    if ((!innerzobjectRef.startsWith(patternInfo.getPrefix()))&&(!innerzobjectRef.endsWith(patternInfo.getSuffix()))) {
                                        builder.addPropertyValue("inner-zobject", new RuntimeBeanReference(innerzobjectRef));
                                    } else {
                                        builder.addPropertyValue("inner-zobject", innerzobjectRef);
                                    }
                                } else {
                                    ManagedMap innerzobject = new ManagedMap();
                                    innerzobjectMapChilds = DomUtils.getChildElementsByTagName(zobjectsChild, "inner-zobject");
                                    if (innerzobjectMapChilds!= null) {
                                        if (innerzobjectMapChilds.size() == 0) {
                                            innerzobjectMapChilds = DomUtils.getChildElements(zobjectsChild);
                                        }
                                        for (Element innerzobjectChild: innerzobjectMapChilds) {
                                            String innerzobjectValueRef = innerzobjectChild.getAttribute("value-ref");
                                            String innerzobjectKeyRef = innerzobjectChild.getAttribute("key-ref");
                                            Object valueObject = null;
                                            Object keyObject = null;
                                            if ((innerzobjectValueRef!= null)&&(!StringUtils.isBlank(innerzobjectValueRef))) {
                                                if ((!innerzobjectValueRef.startsWith(patternInfo.getPrefix()))&&(!innerzobjectValueRef.endsWith(patternInfo.getSuffix()))) {
                                                    valueObject = new RuntimeBeanReference(innerzobjectValueRef);
                                                } else {
                                                    valueObject = innerzobjectValueRef;
                                                }
                                            } else {
                                                valueObject = innerzobjectChild.getTextContent();
                                            }
                                            if ((innerzobjectKeyRef!= null)&&(!StringUtils.isBlank(innerzobjectKeyRef))) {
                                                keyObject = new RuntimeBeanReference(innerzobjectKeyRef);
                                            } else {
                                                keyObject = innerzobjectChild.getAttribute("key");
                                            }
                                            if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                                                keyObject = innerzobjectChild.getTagName();
                                            }
                                            innerzobject.put(keyObject, valueObject);
                                        }
                                    }
                                    zobjects.add(innerzobject);
                                }
                            }
                        }
                    }
                }
                builder.addPropertyValue("zobjects", zobjects);
            }
        }
        if ((element.getAttribute("retryMax")!= null)&&(!StringUtils.isBlank(element.getAttribute("retryMax")))) {
            builder.addPropertyValue("retryMax", element.getAttribute("retryMax"));
        }
        if ((element.getAttribute("username")!= null)&&(!StringUtils.isBlank(element.getAttribute("username")))) {
            builder.addPropertyValue("username", element.getAttribute("username"));
        }
        if ((element.getAttribute("password")!= null)&&(!StringUtils.isBlank(element.getAttribute("password")))) {
            builder.addPropertyValue("password", element.getAttribute("password"));
        }
        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;
        }
    }

}
