/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2008 Bull S.A.S.
 * Copyright (C) 2008 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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.web.tomcat7.versioning;

import java.net.MalformedURLException;
import java.net.URL;

import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.naming.directory.DirContext;

import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ow2.jonas.jmx.JmxService;
import org.ow2.jonas.versioning.VersioningServiceBase;

/**
 * Virtual Context implementation that only handles operations with the default
 * context.
 * @author Frederic Germaneau
 * @author S. Ali Tokmen
 */
public abstract class AbsVirtualContext implements VirtualContextMBean {
    /**
     * Logger.
     */
    private static Log logger = LogFactory.getLog(AbsVirtualContext.class);

    /**
     * Default context.
     */
    protected Context defaultContext = null;

    /**
     * The user (virtual) URI of this context.
     */
    protected String userURI;

    /**
     * Management bean name for this context.
     */
    private String mBeanName;

    /**
     * The JMX server.
     */
    private JmxService jmxService = null;

    /**
     * Creates and registers a virtual context.
     * @param jmxService JMX server.
     * @param userURI User (virtual) URI of this context.
     * @param contextInstance The first context instance, will be mapped as
     *        default context.
     */
    public AbsVirtualContext(final JmxService jmxService, final String userURI, final Context contextInstance) {
        this.userURI = userURI;
        addContext(contextInstance, VersioningServiceBase.DEFAULT);
        Host host = (Host) contextInstance.getParent();
        // J2EEApplication=none since this virtual JNDI binding manager
        // is shared between multiple J2EE applications
        mBeanName = jmxService.getDomainName() + ":j2eeType=WebModule,name=//" + host.getName() + userURI
                + ",J2EEApplication=none,J2EEServer=" + jmxService.getJonasServerName() + ",virtualContext=true";
        logger.debug("New VirtualContext: registering MBean with name : " + mBeanName);
        jmxService.registerMBean(this, mBeanName);
        this.jmxService = jmxService;
    }

    /**
     * Internal call for adding non-default context instances.
     * @param contextInstance Context instance (versioned path).
     * @param policy Policy (extensible).
     * @throws IllegalArgumentException If policy not recognized.
     */
    protected abstract void addContextInternal(Context contextInstance, String policy) throws IllegalArgumentException;

    /**
     * Finds the context object corresponding to a path. This implementation
     * only checks against the default context.
     * @param versionedPath Path to check against.
     * @return Context object corresponding to versionedPath, null if none.
     */
    protected Context findContextObject(final String versionedPath) {
        if (defaultContext != null) {
            if (versionedPath.equals(defaultContext.getPath())) {
                return defaultContext;
            }
        }
        return null;
    }

    /**
     * Adds a context instance to this virtual context using a policy. This
     * implementation will check against the default context and if nothing
     * found call
     * @link{AbsVirtualContext#addContextInternal(Context,String) .
     * @param contextInstance Context instance to add.
     * @param policy Context policy.
     * @throws IllegalArgumentException Policy is invalid.
     */
    public void addContext(final Context contextInstance, final String policy) throws IllegalArgumentException {
        // Check that context's path is not in any list
        if (findContextObject(contextInstance.getPath()) != null) {
            throw new IllegalArgumentException("Context " + contextInstance + " already bound!");
        }

        // Context is not in any lists, add it
        if (VersioningServiceBase.DEFAULT.equals(policy)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Addind default context " + contextInstance.getPath() + " for userURI " + userURI);
            }
            if (null != this.defaultContext) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Setting default context " + defaultContext.getPath() + " as disabled");
                }
                addContextInternal(defaultContext, VersioningServiceBase.DISABLED);
            }
            this.defaultContext = contextInstance;
        } else {
            addContextInternal(contextInstance, policy);
        }
    }

    /**
     * Completely removes this virtual context. Will automatically unregister
     * management beans and unbind the context.
     * @return {@link ContextFinder#unbindVirtualContext(String)}.
     */
    public boolean removeVirtualContext() {
        try {
            jmxService.unregisterMBean(ObjectName.getInstance(mBeanName));
        } catch (MalformedObjectNameException e) {
            logger.error("Error unbinding VirtualContext for URI " + userURI + ", MBean name " + mBeanName, e);
            return false;
        }
        return ContextFinder.unbindVirtualContext(userURI);
    }

    /**
     * Removes a context. This implementation will only check against the
     * default context.
     * @param versionedPath Versioned path of the context.
     * @return true if succeeded, false otherwise.
     */
    public boolean removeContext(final String versionedPath) {
        if (defaultContext != null && versionedPath.equals(defaultContext.getPath())) {
            defaultContext = null;
            return true;
        } else {
            return false;
        }
    }

    /**
     * Checks whether a given context has been registered.
     * @param versionedPath Versioned path of the context.
     * @return true if found, false otherwise.
     */
    public boolean hasContext(final String versionedPath) {
        if (defaultContext != null && versionedPath.equals(defaultContext.getPath())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Dummy definition to keep Tomcat happy.
     * @return null.
     */
    public Context findMappingObject() {
        return defaultContext;
    }

    /**
     * Dummy definition to keep Tomcat happy.
     * @return null.
     */
    public DirContext findStaticResources() {
        return null;
    }

    /**
     * Dummy definition to keep Tomcat happy.
     * @return new String[0].
     */
    public String[] getwelcomeFiles() {
        return new String[0];
    }

    /**
     * Dummy definition to keep Tomcat happy.
     * @return Unique URL for this context.
     */
    public URL getwarURL() {
        try {
            return new URL("file:///dev/null/VirtualWebContainer-" + userURI);
        } catch (MalformedURLException e) {
            throw new IllegalStateException("Cannot create URL", e);
        }
    }
}
