
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.AddActorsToProjectRoleMessageProcessor;
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.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;

public class AddActorsToProjectRoleDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(AddActorsToProjectRoleMessageProcessor.class.getName());
        String configRef = element.getAttribute("config-ref");
        if ((configRef!= null)&&(!StringUtils.isBlank(configRef))) {
            builder.addPropertyValue("moduleObject", configRef);
        }
        Element actorsListElement = null;
        actorsListElement = DomUtils.getChildElementByTagName(element, "actors");
        List<Element> actorsListChilds = null;
        if (actorsListElement!= null) {
            String actorsRef = actorsListElement.getAttribute("ref");
            if ((actorsRef!= null)&&(!StringUtils.isBlank(actorsRef))) {
                if ((!actorsRef.startsWith(patternInfo.getPrefix()))&&(!actorsRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("actors", new RuntimeBeanReference(actorsRef));
                } else {
                    builder.addPropertyValue("actors", actorsRef);
                }
            } else {
                ManagedList actors = new ManagedList();
                actorsListChilds = DomUtils.getChildElementsByTagName(actorsListElement, "actor");
                if (actorsListChilds!= null) {
                    for (Element actorsChild: actorsListChilds) {
                        String valueRef = actorsChild.getAttribute("value-ref");
                        if ((valueRef!= null)&&(!StringUtils.isBlank(valueRef))) {
                            if ((!valueRef.startsWith(patternInfo.getPrefix()))&&(!valueRef.endsWith(patternInfo.getSuffix()))) {
                                actors.add(new RuntimeBeanReference(valueRef));
                            } else {
                                actors.add(valueRef);
                            }
                        } else {
                            actors.add(actorsChild.getTextContent());
                        }
                    }
                }
                builder.addPropertyValue("actors", actors);
            }
        }
        if ((element.getAttribute("projectRoleId")!= null)&&(!StringUtils.isBlank(element.getAttribute("projectRoleId")))) {
            builder.addPropertyValue("projectRoleId", element.getAttribute("projectRoleId"));
        }
        if ((element.getAttribute("projectKey")!= null)&&(!StringUtils.isBlank(element.getAttribute("projectKey")))) {
            builder.addPropertyValue("projectKey", element.getAttribute("projectKey"));
        }
        if ((element.getAttribute("actorType")!= null)&&(!StringUtils.isBlank(element.getAttribute("actorType")))) {
            builder.addPropertyValue("actorType", element.getAttribute("actorType"));
        }
        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;
        }
    }

}
