
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.AddBase64EncodedAttachmentsToIssueMessageProcessor;
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 AddBase64EncodedAttachmentsToIssueDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(AddBase64EncodedAttachmentsToIssueMessageProcessor.class.getName());
        String configRef = element.getAttribute("config-ref");
        if ((configRef!= null)&&(!StringUtils.isBlank(configRef))) {
            builder.addPropertyValue("moduleObject", configRef);
        }
        if ((element.getAttribute("issueKey")!= null)&&(!StringUtils.isBlank(element.getAttribute("issueKey")))) {
            builder.addPropertyValue("issueKey", element.getAttribute("issueKey"));
        }
        Element fileNamesListElement = null;
        fileNamesListElement = DomUtils.getChildElementByTagName(element, "file-names");
        List<Element> fileNamesListChilds = null;
        if (fileNamesListElement!= null) {
            String fileNamesRef = fileNamesListElement.getAttribute("ref");
            if ((fileNamesRef!= null)&&(!StringUtils.isBlank(fileNamesRef))) {
                if ((!fileNamesRef.startsWith(patternInfo.getPrefix()))&&(!fileNamesRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("fileNames", new RuntimeBeanReference(fileNamesRef));
                } else {
                    builder.addPropertyValue("fileNames", fileNamesRef);
                }
            } else {
                ManagedList fileNames = new ManagedList();
                fileNamesListChilds = DomUtils.getChildElementsByTagName(fileNamesListElement, "file-name");
                if (fileNamesListChilds!= null) {
                    for (Element fileNamesChild: fileNamesListChilds) {
                        String valueRef = fileNamesChild.getAttribute("value-ref");
                        if ((valueRef!= null)&&(!StringUtils.isBlank(valueRef))) {
                            if ((!valueRef.startsWith(patternInfo.getPrefix()))&&(!valueRef.endsWith(patternInfo.getSuffix()))) {
                                fileNames.add(new RuntimeBeanReference(valueRef));
                            } else {
                                fileNames.add(valueRef);
                            }
                        } else {
                            fileNames.add(fileNamesChild.getTextContent());
                        }
                    }
                }
                builder.addPropertyValue("fileNames", fileNames);
            }
        }
        Element base64EncodedAttachmentDataListElement = null;
        base64EncodedAttachmentDataListElement = DomUtils.getChildElementByTagName(element, "base64-encoded-attachment-data");
        List<Element> base64EncodedAttachmentDataListChilds = null;
        if (base64EncodedAttachmentDataListElement!= null) {
            String base64EncodedAttachmentDataRef = base64EncodedAttachmentDataListElement.getAttribute("ref");
            if ((base64EncodedAttachmentDataRef!= null)&&(!StringUtils.isBlank(base64EncodedAttachmentDataRef))) {
                if ((!base64EncodedAttachmentDataRef.startsWith(patternInfo.getPrefix()))&&(!base64EncodedAttachmentDataRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("base64EncodedAttachmentData", new RuntimeBeanReference(base64EncodedAttachmentDataRef));
                } else {
                    builder.addPropertyValue("base64EncodedAttachmentData", base64EncodedAttachmentDataRef);
                }
            } else {
                ManagedList base64EncodedAttachmentData = new ManagedList();
                base64EncodedAttachmentDataListChilds = DomUtils.getChildElementsByTagName(base64EncodedAttachmentDataListElement, "base64-encoded-attachment-datum");
                if (base64EncodedAttachmentDataListChilds!= null) {
                    for (Element base64EncodedAttachmentDataChild: base64EncodedAttachmentDataListChilds) {
                        String valueRef = base64EncodedAttachmentDataChild.getAttribute("value-ref");
                        if ((valueRef!= null)&&(!StringUtils.isBlank(valueRef))) {
                            if ((!valueRef.startsWith(patternInfo.getPrefix()))&&(!valueRef.endsWith(patternInfo.getSuffix()))) {
                                base64EncodedAttachmentData.add(new RuntimeBeanReference(valueRef));
                            } else {
                                base64EncodedAttachmentData.add(valueRef);
                            }
                        } else {
                            base64EncodedAttachmentData.add(base64EncodedAttachmentDataChild.getTextContent());
                        }
                    }
                }
                builder.addPropertyValue("base64EncodedAttachmentData", base64EncodedAttachmentData);
            }
        }
        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;
        }
    }

}
