/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2009 France Telecom R&D
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: JNDIInterceptorsComponent.java 19283 2010-02-24 16:16:26Z benoitf $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.jndi.interceptors.impl;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.management.ObjectName;

import org.ow2.carol.jndi.intercept.ContextInterceptor;
import org.ow2.carol.jndi.intercept.InterceptorManager;
import org.ow2.carol.jndi.intercept.manager.SingletonInterceptorManager;
import org.ow2.easybeans.api.EZBServer;
import org.ow2.jonas.ejb3.IEasyBeansService;
import org.ow2.jonas.jmx.JmxService;
import org.ow2.jonas.jndi.checker.api.IResourceCheckerManager;
import org.ow2.jonas.jndi.interceptors.impl.easybeans.ResourceCheckerConfigurationExtension;
import org.ow2.jonas.jndi.interceptors.impl.easybeans.ResourceCheckerInterceptor;
import org.ow2.jonas.lib.bootstrap.JProp;
import org.ow2.jonas.lib.util.JonasObjectName;
import org.ow2.util.event.api.IEventService;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;
import org.ow2.util.url.URLUtils;
import org.ow2.util.xmlconfig.XMLConfiguration;
import org.ow2.util.xmlconfig.XMLConfigurationException;
import org.ow2.util.xmlconfig.properties.SystemPropertyResolver;

/**
 * Component that will create and register JNDI interceptors.
 * @author Florent Benoit
 */
public class JNDIInterceptorsComponent {

    /**
     * Name of the XML file.
     */
    public static final String XML_FILE = "jndi-interceptors.xml";

    /**
     * The name of the JONAS_BASE directory.
     */
    protected static final String JONAS_BASE = JProp.getJonasBase();

    /**
     * Logger.
     */
    private Log logger = LogFactory.getLog(JNDIInterceptorsComponent.class);

    /**
     * Object containing the list of interceptors that have been defined.
     */
    private Interceptors interceptors = null;

    /**
     * Link to the resource checker manager.
     */
    private IResourceCheckerManager resourceCheckerManager = null;

    /**
     * Link to the interceptor manager.
     */
    private InterceptorManager interceptorManager = null;

    /**
     * Optional easybeans service.
     */
    private IEasyBeansService easybeansService = null;

    /**
     * The event service used to register listeners.
     */
    private IEventService eventService = null;

    /**
     * Reference to the JMX service.
     */
    private JmxService jmxService = null;

    /**
     * Default constructor.
     */
    public JNDIInterceptorsComponent() {
        this.interceptors = new Interceptors();

    }

    /**
     * Analyze the JNDI interceptors and register them.
     * @throws JNDIInterceptorsComponentException if start fails.
     */
    public void start() throws JNDIInterceptorsComponentException {
        loadXML();

        // Register the MBeans
        jmxService.loadDescriptors(JNDIInterceptorsComponent.class.getPackage().getName(), getClass().getClassLoader());
        try {
            jmxService.registerModelMBean(this, JonasObjectName.jndiInterceptors(jmxService.getDomainName()));
        } catch (Exception e) {
            // Continue the execution ...
            logger.warn("Cannot register service MBean", e);
        }

        // Register all interceptors
        List<ContextInterceptor> contextInterceptors = interceptors.getContextInterceptors();
        for (ContextInterceptor contextInterceptor : contextInterceptors) {
            registerContextInterceptor(contextInterceptor);
        }

        logger.info("JNDI Interceptors component started");
    }


    /**
     * Load the XML configuration of the interceptor component.
     * @throws JNDIInterceptorsComponentException if the XML file cannot be analyzed
     */
    protected void loadXML() throws JNDIInterceptorsComponentException {

        // Get XML
        File xmlConfigFile = new File(JONAS_BASE + File.separator + "conf" + File.separator + XML_FILE);
        URL xmlconfigFileURL = URLUtils.fileToURL(xmlConfigFile);

        // Parse with XML config
        XMLConfiguration xmlConfiguration = new XMLConfiguration("jndi-interceptors-mapping.xml");

        // Set the source configurations
        xmlConfiguration.addConfigurationFile(xmlconfigFileURL);

        // Resolve properties as system properties
        xmlConfiguration.setPropertyResolver(new SystemPropertyResolver());

        // Use a map for some properties
        Map<String, Object> contextualInstances = new HashMap<String, Object>();

        // Add the Resource Checker Manager as new property
        contextualInstances.put("RCManager", resourceCheckerManager);

        // Add the JMXService as new property
        contextualInstances.put("jmxService", jmxService);


        // Sets the contextual instances
        xmlConfiguration.setContextualInstances(contextualInstances);

        // Start configuration of this object
        try {
            xmlConfiguration.configure(this);
        } catch (XMLConfigurationException e) {
            throw new JNDIInterceptorsComponentException("Cannot configure the Interceptor component", e);
        }

    }

    /**
     * Register the given context interceptor.
     * @param contextInterceptor the interceptor
     */
    protected void registerContextInterceptor(final ContextInterceptor contextInterceptor) {
        logger.debug("Registering the context interceptor ''{0}''", contextInterceptor);

        // TODO: change to instance of interceptor manager but the injected
        // interceptor manager in the InterceptorInitialContextFactory should be
        // the same value
        SingletonInterceptorManager.getInterceptorManager().registerContextInterceptor(contextInterceptor);

        try {
            jmxService.registerModelMBean(contextInterceptor, getObjectName(contextInterceptor));
        } catch (Exception e) {
            // Continue the execution, MBean are optional ...
            logger.debug("Cannot register context interceptor MBean", e);
        }
    }

    /**
     * Unregister the given context interceptor.
     * @param contextInterceptor the interceptor
     */
    protected void unregisterContextInterceptor(final ContextInterceptor contextInterceptor) {
        logger.debug("Unregistering the context interceptor ''{0}''", contextInterceptor);

        SingletonInterceptorManager.getInterceptorManager().unregisterContextInterceptor(contextInterceptor);

        try {
            jmxService.unregisterModelMBean(getObjectName(contextInterceptor));
        } catch (Exception e) {
            // Continue the execution, MBean are optional ...
            logger.debug("Cannot unregister  context interceptor MBean", e);
        }

    }

    /**
     * @param contextInterceptor the interceptor instance
     * @return the objectname built for the given interceptor
     */
    protected ObjectName getObjectName(final ContextInterceptor contextInterceptor) {
        ObjectName oName = JonasObjectName.jndiContextInterceptor(jmxService.getDomainName(), contextInterceptor.getClass()
                .getName());
        if (contextInterceptor instanceof AbsContextInterceptor) {
            ObjectName tmpName = ((AbsContextInterceptor) contextInterceptor).getObjectName(jmxService.getDomainName());
            if (tmpName != null) {
                oName = tmpName;
            }
        }
        return oName;
    }

    /**
     * Stop the JNDI interceptors.
     * @throws JNDIInterceptorsComponentException if component cannot be stopped
     */
    public void stop() throws JNDIInterceptorsComponentException {

        // Unregister the Service MBean
        jmxService.unregisterModelMBean(JonasObjectName.jndiInterceptors(jmxService.getDomainName()));

        // Unregister all interceptors
        List<ContextInterceptor> contextInterceptors = interceptors.getContextInterceptors();
        for (ContextInterceptor contextInterceptor : contextInterceptors) {
            unregisterContextInterceptor(contextInterceptor);
        }

        logger.info("JNDI Interceptors component stopped");
    }

    /**
     * @return interceptors object that is managing the context interceptors.
     */
    public Interceptors getInterceptors() {
        return interceptors;
    }

    /**
     * Sets the interceptors manager object.
     * @param interceptors the interceptors object
     */
    public void setInterceptors(final Interceptors interceptors) {
        this.interceptors = interceptors;
    }

    /**
     * @return the resource checker manager
     */
    public IResourceCheckerManager getResourceCheckerManager() {
        return resourceCheckerManager;
    }

    /**
     * Sets the resource checker manager.
     * @param resourceCheckerManager the given instance
     */
    public void setResourceCheckerManager(final IResourceCheckerManager resourceCheckerManager) {
        this.resourceCheckerManager = resourceCheckerManager;
    }

    /**
     * Unset the resource checker manager.
     */
    public void unsetResourceCheckerManager() {
        this.resourceCheckerManager = null;
    }

    /**
     * Sets the interceptor manager.
     * @param interceptorManager the given instance
     */
    public void setInterceptorManager(final InterceptorManager interceptorManager) {
        this.interceptorManager = interceptorManager;
    }

    /**
     * Unset the interceptor manager.
     */
    public void unsetInterceptorManager() {
        this.interceptorManager = null;
    }


    /**
     * Sets the easybeans service.
     * @param easybeansService the given instance
     */
    public void setEasyBeansService(final IEasyBeansService easybeansService) {
        this.easybeansService = easybeansService;

        // Get server
        EZBServer server = easybeansService.getEasyBeansServer();

        // Add global interceptor
        server.getGlobalInterceptorsClasses().add(ResourceCheckerInterceptor.class);

        // register extension
        ResourceCheckerConfigurationExtension extension = new ResourceCheckerConfigurationExtension(resourceCheckerManager);
        server.getServerConfig().addExtensionFactory(extension);
    }

    /**
     * Unset the easybeans service.
     */
    public void unsetEasyBeansService() {
        this.easybeansService = null;
    }


    /**
     * Callback invoked when an EventService becomes available.
     * @param eventService the event service
     */
    public void bindEventService(final IEventService eventService) {
        this.eventService = eventService;
    }

    /**
     * Callback invoked when the used EventService becomes unavalable.
     * @param eventService disposed service
     */
    public void unbindEventService(final IEventService eventService) {
        this.eventService = null;
    }

    /**
     * @param jmxService the jmxService to set
     */
    public void setJmxService(final JmxService jmxService) {
        this.jmxService = jmxService;
    }


}
