
package org.mule.modules.boxnet.config;

import org.apache.commons.lang.StringUtils;
import org.mule.api.lifecycle.Disposable;
import org.mule.api.lifecycle.Initialisable;
import org.mule.config.spring.MuleHierarchicalBeanDefinitionParserDelegate;
import org.mule.config.spring.parsers.generic.AutoIdUtils;
import org.mule.modules.boxnet.adapters.BoxNetModuleLifecycleAdapter;
import org.mule.util.TemplateParser;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

public class BoxNetModuleConfigDefinitionParser
    implements BeanDefinitionParser
{

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

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

    public BeanDefinition parse(Element element, ParserContext parserContent) {
        String name = element.getAttribute("name");
        if ((name == null)||StringUtils.isBlank(name)) {
            element.setAttribute("name", AutoIdUtils.getUniqueName(element, "mule-bean"));
        }
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(BoxNetModuleLifecycleAdapter.class.getName());
        if (Initialisable.class.isAssignableFrom(BoxNetModuleLifecycleAdapter.class)) {
            builder.setInitMethodName(Initialisable.PHASE_NAME);
        }
        if (Disposable.class.isAssignableFrom(BoxNetModuleLifecycleAdapter.class)) {
            builder.setDestroyMethodName(Disposable.PHASE_NAME);
        }
        if ((element.getAttribute("apiKey")!= null)&&(!StringUtils.isBlank(element.getAttribute("apiKey")))) {
            builder.addPropertyValue("apiKey", element.getAttribute("apiKey"));
        }
        if ((element.getAttribute("usesCallback")!= null)&&(!StringUtils.isBlank(element.getAttribute("usesCallback")))) {
            builder.addPropertyValue("usesCallback", element.getAttribute("usesCallback"));
        }
        if ((element.getAttribute("callbackPath")!= null)&&(!StringUtils.isBlank(element.getAttribute("callbackPath")))) {
            builder.addPropertyValue("callbackPath", element.getAttribute("callbackPath"));
        }
        if ((element.getAttribute("callbackPort")!= null)&&(!StringUtils.isBlank(element.getAttribute("callbackPort")))) {
            builder.addPropertyValue("callbackPort", element.getAttribute("callbackPort"));
        }
        BeanDefinition definition = builder.getBeanDefinition();
        definition.setAttribute(MuleHierarchicalBeanDefinitionParserDelegate.MULE_NO_RECURSE, Boolean.TRUE);
        return definition;
    }

}
