
package org.mule.module.paypal.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.module.paypal.config.DoDirectPaymentMessageProcessor;
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 DoDirectPaymentDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(DoDirectPaymentMessageProcessor.class.getName());
        String configRef = element.getAttribute("config-ref");
        if ((configRef!= null)&&(!StringUtils.isBlank(configRef))) {
            builder.addPropertyValue("moduleObject", configRef);
        }
        if ((element.getAttribute("ipAddress")!= null)&&(!StringUtils.isBlank(element.getAttribute("ipAddress")))) {
            builder.addPropertyValue("ipAddress", element.getAttribute("ipAddress"));
        }
        Element cardDetailsListElement = null;
        cardDetailsListElement = DomUtils.getChildElementByTagName(element, "card-details");
        List<Element> cardDetailsListChilds = null;
        if (cardDetailsListElement!= null) {
            String cardDetailsRef = cardDetailsListElement.getAttribute("ref");
            if ((cardDetailsRef!= null)&&(!StringUtils.isBlank(cardDetailsRef))) {
                if ((!cardDetailsRef.startsWith(patternInfo.getPrefix()))&&(!cardDetailsRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("cardDetails", new RuntimeBeanReference(cardDetailsRef));
                } else {
                    builder.addPropertyValue("cardDetails", cardDetailsRef);
                }
            } else {
                ManagedMap cardDetails = new ManagedMap();
                cardDetailsListChilds = DomUtils.getChildElementsByTagName(cardDetailsListElement, "card-detail");
                if (cardDetailsListChilds!= null) {
                    if (cardDetailsListChilds.size() == 0) {
                        cardDetailsListChilds = DomUtils.getChildElements(cardDetailsListElement);
                    }
                    for (Element cardDetailsChild: cardDetailsListChilds) {
                        String cardDetailsValueRef = cardDetailsChild.getAttribute("value-ref");
                        String cardDetailsKeyRef = cardDetailsChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((cardDetailsValueRef!= null)&&(!StringUtils.isBlank(cardDetailsValueRef))) {
                            valueObject = new RuntimeBeanReference(cardDetailsValueRef);
                        } else {
                            valueObject = cardDetailsChild.getTextContent();
                        }
                        if ((cardDetailsKeyRef!= null)&&(!StringUtils.isBlank(cardDetailsKeyRef))) {
                            keyObject = new RuntimeBeanReference(cardDetailsKeyRef);
                        } else {
                            keyObject = cardDetailsChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = cardDetailsChild.getTagName();
                        }
                        cardDetails.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("cardDetails", cardDetails);
            }
        }
        Element paymentDetailsListElement = null;
        paymentDetailsListElement = DomUtils.getChildElementByTagName(element, "payment-details");
        List<Element> paymentDetailsListChilds = null;
        if (paymentDetailsListElement!= null) {
            String paymentDetailsRef = paymentDetailsListElement.getAttribute("ref");
            if ((paymentDetailsRef!= null)&&(!StringUtils.isBlank(paymentDetailsRef))) {
                if ((!paymentDetailsRef.startsWith(patternInfo.getPrefix()))&&(!paymentDetailsRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("paymentDetails", new RuntimeBeanReference(paymentDetailsRef));
                } else {
                    builder.addPropertyValue("paymentDetails", paymentDetailsRef);
                }
            } else {
                ManagedMap paymentDetails = new ManagedMap();
                paymentDetailsListChilds = DomUtils.getChildElementsByTagName(paymentDetailsListElement, "payment-detail");
                if (paymentDetailsListChilds!= null) {
                    if (paymentDetailsListChilds.size() == 0) {
                        paymentDetailsListChilds = DomUtils.getChildElements(paymentDetailsListElement);
                    }
                    for (Element paymentDetailsChild: paymentDetailsListChilds) {
                        String paymentDetailsValueRef = paymentDetailsChild.getAttribute("value-ref");
                        String paymentDetailsKeyRef = paymentDetailsChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((paymentDetailsValueRef!= null)&&(!StringUtils.isBlank(paymentDetailsValueRef))) {
                            valueObject = new RuntimeBeanReference(paymentDetailsValueRef);
                        } else {
                            valueObject = paymentDetailsChild.getTextContent();
                        }
                        if ((paymentDetailsKeyRef!= null)&&(!StringUtils.isBlank(paymentDetailsKeyRef))) {
                            keyObject = new RuntimeBeanReference(paymentDetailsKeyRef);
                        } else {
                            keyObject = paymentDetailsChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = paymentDetailsChild.getTagName();
                        }
                        paymentDetails.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("paymentDetails", paymentDetails);
            }
        }
        if (element.hasAttribute("paymentAction")) {
            builder.addPropertyValue("paymentAction", element.getAttribute("paymentAction"));
        }
        if ((element.getAttribute("setReturnFMFDetails")!= null)&&(!StringUtils.isBlank(element.getAttribute("setReturnFMFDetails")))) {
            builder.addPropertyValue("setReturnFMFDetails", element.getAttribute("setReturnFMFDetails"));
        }
        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;
        }
    }

}
