
package org.mule.module.linkedin.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.linkedin.config.SearchPeopleWithFacetsMessageProcessor;
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 SearchPeopleWithFacetsDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(SearchPeopleWithFacetsMessageProcessor.class.getName());
        String configRef = element.getAttribute("config-ref");
        if ((configRef!= null)&&(!StringUtils.isBlank(configRef))) {
            builder.addPropertyValue("moduleObject", configRef);
        }
        if ((element.getAttribute("accessToken")!= null)&&(!StringUtils.isBlank(element.getAttribute("accessToken")))) {
            builder.addPropertyValue("accessToken", element.getAttribute("accessToken"));
        }
        if ((element.getAttribute("accessTokenSecret")!= null)&&(!StringUtils.isBlank(element.getAttribute("accessTokenSecret")))) {
            builder.addPropertyValue("accessTokenSecret", element.getAttribute("accessTokenSecret"));
        }
        Element searchParametersListElement = null;
        searchParametersListElement = DomUtils.getChildElementByTagName(element, "search-parameters");
        List<Element> searchParametersListChilds = null;
        if (searchParametersListElement!= null) {
            String searchParametersRef = searchParametersListElement.getAttribute("ref");
            if ((searchParametersRef!= null)&&(!StringUtils.isBlank(searchParametersRef))) {
                if ((!searchParametersRef.startsWith(patternInfo.getPrefix()))&&(!searchParametersRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("searchParameters", new RuntimeBeanReference(searchParametersRef));
                } else {
                    builder.addPropertyValue("searchParameters", searchParametersRef);
                }
            } else {
                ManagedMap searchParameters = new ManagedMap();
                searchParametersListChilds = DomUtils.getChildElementsByTagName(searchParametersListElement, "search-parameter");
                if (searchParametersListChilds!= null) {
                    if (searchParametersListChilds.size() == 0) {
                        searchParametersListChilds = DomUtils.getChildElements(searchParametersListElement);
                    }
                    for (Element searchParametersChild: searchParametersListChilds) {
                        String searchParametersValueRef = searchParametersChild.getAttribute("value-ref");
                        String searchParametersKeyRef = searchParametersChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((searchParametersValueRef!= null)&&(!StringUtils.isBlank(searchParametersValueRef))) {
                            valueObject = new RuntimeBeanReference(searchParametersValueRef);
                        } else {
                            valueObject = searchParametersChild.getTextContent();
                        }
                        if ((searchParametersKeyRef!= null)&&(!StringUtils.isBlank(searchParametersKeyRef))) {
                            keyObject = new RuntimeBeanReference(searchParametersKeyRef);
                        } else {
                            keyObject = searchParametersChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = searchParametersChild.getTagName();
                        }
                        searchParameters.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("searchParameters", searchParameters);
            }
        }
        Element profileFieldsListElement = null;
        profileFieldsListElement = DomUtils.getChildElementByTagName(element, "profile-fields");
        List<Element> profileFieldsListChilds = null;
        if (profileFieldsListElement!= null) {
            String profileFieldsRef = profileFieldsListElement.getAttribute("ref");
            if ((profileFieldsRef!= null)&&(!StringUtils.isBlank(profileFieldsRef))) {
                if ((!profileFieldsRef.startsWith(patternInfo.getPrefix()))&&(!profileFieldsRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("profileFields", new RuntimeBeanReference(profileFieldsRef));
                } else {
                    builder.addPropertyValue("profileFields", profileFieldsRef);
                }
            } else {
                ManagedList profileFields = new ManagedList();
                profileFieldsListChilds = DomUtils.getChildElementsByTagName(profileFieldsListElement, "profile-field");
                if (profileFieldsListChilds!= null) {
                    for (Element profileFieldsChild: profileFieldsListChilds) {
                        String valueRef = profileFieldsChild.getAttribute("value-ref");
                        if ((valueRef!= null)&&(!StringUtils.isBlank(valueRef))) {
                            profileFields.add(new RuntimeBeanReference(valueRef));
                        } else {
                            profileFields.add(profileFieldsChild.getTextContent());
                        }
                    }
                }
                builder.addPropertyValue("profileFields", profileFields);
            }
        }
        if ((element.getAttribute("start")!= null)&&(!StringUtils.isBlank(element.getAttribute("start")))) {
            builder.addPropertyValue("start", element.getAttribute("start"));
        }
        if ((element.getAttribute("count")!= null)&&(!StringUtils.isBlank(element.getAttribute("count")))) {
            builder.addPropertyValue("count", element.getAttribute("count"));
        }
        if (element.hasAttribute("sortOrder")) {
            builder.addPropertyValue("sortOrder", element.getAttribute("sortOrder"));
        }
        Element facetsListElement = null;
        facetsListElement = DomUtils.getChildElementByTagName(element, "facets");
        List<Element> facetsListChilds = null;
        if (facetsListElement!= null) {
            String facetsRef = facetsListElement.getAttribute("ref");
            if ((facetsRef!= null)&&(!StringUtils.isBlank(facetsRef))) {
                if ((!facetsRef.startsWith(patternInfo.getPrefix()))&&(!facetsRef.endsWith(patternInfo.getSuffix()))) {
                    builder.addPropertyValue("facets", new RuntimeBeanReference(facetsRef));
                } else {
                    builder.addPropertyValue("facets", facetsRef);
                }
            } else {
                ManagedMap facets = new ManagedMap();
                facetsListChilds = DomUtils.getChildElementsByTagName(facetsListElement, "facet");
                if (facetsListChilds!= null) {
                    if (facetsListChilds.size() == 0) {
                        facetsListChilds = DomUtils.getChildElements(facetsListElement);
                    }
                    for (Element facetsChild: facetsListChilds) {
                        String facetsValueRef = facetsChild.getAttribute("value-ref");
                        String facetsKeyRef = facetsChild.getAttribute("key-ref");
                        Object valueObject = null;
                        Object keyObject = null;
                        if ((facetsValueRef!= null)&&(!StringUtils.isBlank(facetsValueRef))) {
                            valueObject = new RuntimeBeanReference(facetsValueRef);
                        } else {
                            valueObject = facetsChild.getTextContent();
                        }
                        if ((facetsKeyRef!= null)&&(!StringUtils.isBlank(facetsKeyRef))) {
                            keyObject = new RuntimeBeanReference(facetsKeyRef);
                        } else {
                            keyObject = facetsChild.getAttribute("key");
                        }
                        if ((keyObject == null)||((keyObject instanceof String)&&StringUtils.isBlank(((String) keyObject)))) {
                            keyObject = facetsChild.getTagName();
                        }
                        facets.put(keyObject, valueObject);
                    }
                }
                builder.addPropertyValue("facets", facets);
            }
        }
        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;
        }
    }

}
