
package org.mule.module.jira.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.module.jira.processors.CreateIssueWithSecurityLevelMessageProcessor;
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 CreateIssueWithSecurityLevelDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(CreateIssueWithSecurityLevelMessageProcessor.class.getName());
        String configRef = element.getAttribute("config-ref");
        if ((configRef!= null)&&(!StringUtils.isBlank(configRef))) {
            builder.addPropertyValue("moduleObject", configRef);
        }
        if ((element.getAttribute("assignee")!= null)&&(!StringUtils.isBlank(element.getAttribute("assignee")))) {
            builder.addPropertyValue("assignee", element.getAttribute("assignee"));
        }
        if ((element.getAttribute("summary")!= null)&&(!StringUtils.isBlank(element.getAttribute("summary")))) {
            builder.addPropertyValue("summary", element.getAttribute("summary"));
        }
        if ((element.getAttribute("description")!= null)&&(!StringUtils.isBlank(element.getAttribute("description")))) {
            builder.addPropertyValue("description", element.getAttribute("description"));
        }
        if ((element.getAttribute("dueDate")!= null)&&(!StringUtils.isBlank(element.getAttribute("dueDate")))) {
            builder.addPropertyValue("dueDate", element.getAttribute("dueDate"));
        }
        if ((element.getAttribute("environment")!= null)&&(!StringUtils.isBlank(element.getAttribute("environment")))) {
            builder.addPropertyValue("environment", element.getAttribute("environment"));
        }
        if ((element.getAttribute("priority")!= null)&&(!StringUtils.isBlank(element.getAttribute("priority")))) {
            builder.addPropertyValue("priority", element.getAttribute("priority"));
        }
        if ((element.getAttribute("project")!= null)&&(!StringUtils.isBlank(element.getAttribute("project")))) {
            builder.addPropertyValue("project", element.getAttribute("project"));
        }
        if ((element.getAttribute("reporter")!= null)&&(!StringUtils.isBlank(element.getAttribute("reporter")))) {
            builder.addPropertyValue("reporter", element.getAttribute("reporter"));
        }
        if ((element.getAttribute("type")!= null)&&(!StringUtils.isBlank(element.getAttribute("type")))) {
            builder.addPropertyValue("type", element.getAttribute("type"));
        }
        if ((element.getAttribute("votes")!= null)&&(!StringUtils.isBlank(element.getAttribute("votes")))) {
            builder.addPropertyValue("votes", element.getAttribute("votes"));
        }
        Element customFieldsListElement = null;
        customFieldsListElement = DomUtils.getChildElementByTagName(element, "custom-fields");
        List<Element> customFieldsMapChilds = null;
        if (customFieldsListElement!= null) {
            String customFieldsRef = customFieldsListElement.getAttribute("ref");
            if ((customFieldsRef!= null)&&(!StringUtils.isBlank(customFieldsRef))) {
                if ((!customFieldsRef.startsWith(patternInfo.getPrefix()))&&(!customFieldsRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("customFields", new RuntimeBeanReference(customFieldsRef));
                } else {
                    builder.addPropertyValue("customFields", customFieldsRef);
                }
            } else {
                ManagedMap customFields = new ManagedMap();
                customFieldsMapChilds = DomUtils.getChildElementsByTagName(customFieldsListElement, "custom-field");
                if (customFieldsMapChilds!= null) {
                    if (customFieldsMapChilds.size() == 0) {
                        customFieldsMapChilds = DomUtils.getChildElements(customFieldsListElement);
                    }
                    for (Element customFieldsChild: customFieldsMapChilds) {
                        String customFieldsValueRef = customFieldsChild.getAttribute("value-ref");
                        String customFieldsKeyRef = customFieldsChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((customFieldsValueRef!= null)&&(!StringUtils.isBlank(customFieldsValueRef))) {
                            if ((!customFieldsValueRef.startsWith(patternInfo.getPrefix()))&&(!customFieldsValueRef.endsWith(patternInfo.getSuffix()))) {
                                valueObject = new RuntimeBeanReference(customFieldsValueRef);
                            } else {
                                valueObject = customFieldsValueRef;
                            }
                        } else {
                            valueObject = customFieldsChild.getTextContent();
                        }
                        if ((customFieldsKeyRef!= null)&&(!StringUtils.isBlank(customFieldsKeyRef))) {
                            keyObject = new RuntimeBeanReference(customFieldsKeyRef);
                        } else {
                            keyObject = customFieldsChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = customFieldsChild.getTagName();
                        }
                        customFields.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("customFields", customFields);
            }
        }
        if ((element.getAttribute("securityLevelId")!= null)&&(!StringUtils.isBlank(element.getAttribute("securityLevelId")))) {
            builder.addPropertyValue("securityLevelId", element.getAttribute("securityLevelId"));
        }
        if ((element.getAttribute("componentName")!= null)&&(!StringUtils.isBlank(element.getAttribute("componentName")))) {
            builder.addPropertyValue("componentName", element.getAttribute("componentName"));
        }
        if ((element.getAttribute("componentId")!= null)&&(!StringUtils.isBlank(element.getAttribute("componentId")))) {
            builder.addPropertyValue("componentId", element.getAttribute("componentId"));
        }
        if ((element.getAttribute("retryMax")!= null)&&(!StringUtils.isBlank(element.getAttribute("retryMax")))) {
            builder.addPropertyValue("retryMax", element.getAttribute("retryMax"));
        }
        if ((element.getAttribute("connectionUser")!= null)&&(!StringUtils.isBlank(element.getAttribute("connectionUser")))) {
            builder.addPropertyValue("connectionUser", element.getAttribute("connectionUser"));
        }
        if ((element.getAttribute("connectionPassword")!= null)&&(!StringUtils.isBlank(element.getAttribute("connectionPassword")))) {
            builder.addPropertyValue("connectionPassword", element.getAttribute("connectionPassword"));
        }
        if ((element.getAttribute("connectionAddress")!= null)&&(!StringUtils.isBlank(element.getAttribute("connectionAddress")))) {
            builder.addPropertyValue("connectionAddress", element.getAttribute("connectionAddress"));
        }
        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;
        }
    }

}
