
package org.mule.modules.salesforce.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.salesforce.config.UpsertBulkMessageProcessor;
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 UpsertBulkDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(UpsertBulkMessageProcessor.class.getName());
        String configRef = element.getAttribute("config-ref");
        if ((configRef!= null)&&(!StringUtils.isBlank(configRef))) {
            builder.addPropertyValue("moduleObject", configRef);
        }
        if ((element.getAttribute("type")!= null)&&(!StringUtils.isBlank(element.getAttribute("type")))) {
            builder.addPropertyValue("type", element.getAttribute("type"));
        }
        if ((element.getAttribute("externalIdFieldName")!= null)&&(!StringUtils.isBlank(element.getAttribute("externalIdFieldName")))) {
            builder.addPropertyValue("externalIdFieldName", element.getAttribute("externalIdFieldName"));
        }
        Element objectsListElement = null;
        objectsListElement = DomUtils.getChildElementByTagName(element, "objects");
        List<Element> objectsListChilds = null;
        if (objectsListElement!= null) {
            String objectsRef = objectsListElement.getAttribute("ref");
            if ((objectsRef!= null)&&(!StringUtils.isBlank(objectsRef))) {
                if ((!objectsRef.startsWith(patternInfo.getPrefix()))&&(!objectsRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("objects", new RuntimeBeanReference(objectsRef));
                } else {
                    builder.addPropertyValue("objects", objectsRef);
                }
            } else {
                ManagedList objects = new ManagedList();
                objectsListChilds = DomUtils.getChildElementsByTagName(objectsListElement, "object");
                if (objectsListChilds!= null) {
                    for (Element objectsChild: objectsListChilds) {
                        String valueRef = objectsChild.getAttribute("value-ref");
                        if ((valueRef!= null)&&(!StringUtils.isBlank(valueRef))) {
                            objects.add(new RuntimeBeanReference(valueRef));
                        } else {
                            List<Element> innerobjectListChilds = null;
                            if (objectsChild!= null) {
                                String innerobjectRef = objectsChild.getAttribute("ref");
                                if ((innerobjectRef!= null)&&(!StringUtils.isBlank(innerobjectRef))) {
                                    if ((!innerobjectRef.startsWith(patternInfo.getPrefix()))&&(!innerobjectRef.endsWith(patternInfo.getSuffix()))) {
                                        builder.addPropertyValue("inner-object", new RuntimeBeanReference(innerobjectRef));
                                    } else {
                                        builder.addPropertyValue("inner-object", innerobjectRef);
                                    }
                                } else {
                                    ManagedMap innerobject = new ManagedMap();
                                    innerobjectListChilds = DomUtils.getChildElementsByTagName(objectsChild, "inner-object");
                                    if (innerobjectListChilds!= null) {
                                        if (innerobjectListChilds.size() == 0) {
                                            innerobjectListChilds = DomUtils.getChildElements(objectsChild);
                                        }
                                        for (Element innerobjectChild: innerobjectListChilds) {
                                            String innerobjectValueRef = innerobjectChild.getAttribute("value-ref");
                                            String innerobjectKeyRef = innerobjectChild.getAttribute("key-ref");
                                            Object valueObject = null;
                                            Object keyObject = null;
                                            if ((innerobjectValueRef!= null)&&(!StringUtils.isBlank(innerobjectValueRef))) {
                                                valueObject = new RuntimeBeanReference(innerobjectValueRef);
                                            } else {
                                                valueObject = innerobjectChild.getTextContent();
                                            }
                                            if ((innerobjectKeyRef!= null)&&(!StringUtils.isBlank(innerobjectKeyRef))) {
                                                keyObject = new RuntimeBeanReference(innerobjectKeyRef);
                                            } else {
                                                keyObject = innerobjectChild.getAttribute("key");
                                            }
                                            if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                                                keyObject = innerobjectChild.getTagName();
                                            }
                                            innerobject.put(keyObject, valueObject);
                                        }
                                    }
                                    objects.add(innerobject);
                                }
                            }
                        }
                    }
                }
                builder.addPropertyValue("objects", objects);
            }
        }
        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"));
        }
        if ((element.getAttribute("securityToken")!= null)&&(!StringUtils.isBlank(element.getAttribute("securityToken")))) {
            builder.addPropertyValue("securityToken", element.getAttribute("securityToken"));
        }
        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;
        }
    }

}
