/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2008 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * Application Versioning System
 * Copyright (C) 2008 France Telecom R&D
 *
 * 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 1any 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.tomcat6.versioning;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.connector.Request;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.buf.MessageBytes;
import org.ow2.jonas.jmx.JmxService;
import org.ow2.jonas.web.base.BaseWebContainerService;

/**
 * Manages virtual contexts.
 *
 * @author Frederic Germaneau
 * @author S. Ali Tokmen
 */
public final class ContextFinder {

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

    /**
     * Virtual contexts corresponding to URIs.
     */
    private static Map<String, VirtualContext> contextURIMapping = new HashMap<String, VirtualContext>();

    /**
     * Reference to a MBean server.
     */
    private static JmxService jmxService = null;

    /**
     * Web container.
     */
    private static BaseWebContainerService webContainer = null;

    /**
     * @param jmxService  JMX service to set.
     */
    public static void setJmxService(final JmxService jmxService) {
        ContextFinder.jmxService = jmxService;
    }

    /**
     * This is a static class.
     */
    private ContextFinder() {
        // Nothing
    }

    /**
     * @param webContainer  JOnAS web container to set.
     */
    public static void setParent(final BaseWebContainerService webContainer) {
        ContextFinder.webContainer = webContainer;
    }

    /**
     * Gets the context URI for a given request using the Context URI mapping.
     *
     * @param decodedURI  Decoded URI.
     * @param connector   Connector.
     * @param req         Request received by the HTTP server.
     * @param vpb         Bean to use for saving information about resolving paths.
     *
     * @return  Response bytes.
     *
     * @throws IOException If duplication of the decodedURI fails.
     */
    public static MessageBytes getContextURI(final MessageBytes decodedURI, final Connector connector,
            final Request req, final VersionedPathBean vpb) throws IOException {
        MessageBytes contextURI = decodedURI;

        if (logger.isDebugEnabled()) {
            logger.debug("Starting getContextURI...");
            logger.debug("\tdecodedURI = " + decodedURI.toString());
            logger.debug("\tcontextURI = " + contextURI.toString());
        }

        if(webContainer.isVersioningEnabled()) {
            int firstSlash;
            if (decodedURI.getLength() == 1) {
                // Special handling for the root context
                firstSlash = decodedURI.indexOf('/', 0);
                if (firstSlash != 0 && vpb != null) {
                    vpb.setUserPathEndWithSlash(false);
                }
            } else {
                firstSlash = decodedURI.indexOf('/', 1);
            }
            String userPath;
            if (firstSlash > 0) {
                // There a slash at the end of the context root of the URI,
                // forget about it
                userPath = new String(decodedURI.getCharChunk().getChars(), 0, firstSlash);
            } else {
                userPath = new String(decodedURI.getCharChunk().getChars(), 0, decodedURI.getLength());
                if (decodedURI.getLength() != 1 && vpb != null) {
                    vpb.setUserPathEndWithSlash(false);
                }
            }
            VirtualContext vctx = contextURIMapping.get(userPath);
            if (vctx != null) {
                contextURI = MessageBytes.newInstance();
                contextURI.duplicate(decodedURI);
                String versionedPath = vctx.findContext(req);
                StringBuffer versionedURI = new StringBuffer();
                if (versionedPath == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("No version found for virtual context : " + userPath);
                    }
                    versionedURI.append(userPath);
                    versionedURI.append("-invalid-version/");
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Found versioned context : " + versionedPath);
                    }
                    if(vpb != null) {
                        vpb.setUserPath(userPath);
                        vpb.setVersionedPath(versionedPath);
                    }
                    versionedURI.append(versionedPath);
                    versionedURI.append('/');
                    if (decodedURI.getLength() - userPath.length() - 1 > 0) {
                        versionedURI.append(decodedURI.getCharChunk().getChars(), userPath.length() + 1,
                                decodedURI.getLength() - userPath.length() - 1);
                    }
                }
                contextURI.setChars(versionedURI.toString().toCharArray(), 0, versionedURI.length());
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("No virtual context for URI : " + userPath);
                }
            }
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Finished getContextURI");
            logger.debug("\tdecodedURI = " + decodedURI.toString());
            logger.debug("\tcontextURI = " + contextURI.toString());
        }

        return contextURI;
    }

    /**
     * Binds a new context root. If the userURI is an existing versioned path,
     * adds the context to the map using the given policy. Else, creates a new
     * versioned context with this root as default.
     *
     * @param appName      Name of the application the context belongs to.
     * @param userURI      User URI.
     * @param contextRoot  Versioned context root.
     * @param policy       Policy to use, ignored if new virtual context.
     *
     * @return true if versioning enabled, false otherwise.
     */
    public static boolean bindContextRoot(final String appName, final String userURI,
            final Context contextRoot, final String policy) {
        if(webContainer.isVersioningEnabled()) {
            if (!contextURIMapping.containsKey(userURI)) {
                VirtualContext newContext = new VirtualContext(jmxService, userURI, contextRoot);
                contextURIMapping.put(userURI, newContext);
                webContainer.getVersioningService().addContext(appName, newContext.getMBeanName());
            } else {
                contextURIMapping.get(userURI).addContext(contextRoot, policy);
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param userContextRoot  User (virtual) context root to list.
     *
     * @return Context root information for a given virtual (user) URI.
     */
    public static Map<String, String> readContextRoot(final String userContextRoot) {
        if(webContainer.isVersioningEnabled()) {
            VirtualContext context = contextURIMapping.get(userContextRoot);
            if(context == null) {
                return null;
            } else {
                return context.getContexts();
            }
        } else {
            return null;
        }
    }

    /**
     * Unbinds a context root.
     *
     * @param userURI      User (virtual) URI to unbind from.
     * @param contextRoot  Context root to unbind.
     *
     * @return true if succeeded, false otherwise.
     */
    public static boolean unbindContextRoot(final String userURI, final Context contextRoot) {
        return unbindContextRoot(userURI, contextRoot.getPath());
    }

    /**
     * Unbinds a versioned path.
     *
     * @param userURI        User (virtual) URI to unbind from.
     * @param versionedPath  Versioned path to unbind.
     *
     * @return true if succeeded, false otherwise.
     */
    public static boolean unbindContextRoot(final String userURI, final String versionedPath) {
        if(webContainer.isVersioningEnabled()) {
            VirtualContext context = contextURIMapping.get(userURI);
            if(context == null) {
                return false;
            } else {
                return context.removeContext(versionedPath);
            }
        } else {
            return false;
        }
    }

    /**
     * Unbinds a versioned path.
     *
     * @param versionedPath  Versioned path to unbind.
     *
     * @return true if succeeded, false otherwise.
     */
    public static boolean unbindContextRoot(final Context contextRoot) {
        return unbindContextRoot(contextRoot.getPath());
    }

    /**
     * Unbinds a versioned path.
     *
     * @param versionedPath  Versioned path to unbind.
     *
     * @return true if succeeded, false otherwise.
     */
    public static boolean unbindContextRoot(final String contextRoot) {
        if(webContainer.isVersioningEnabled()) {
            for(Map.Entry<String, VirtualContext> entry : contextURIMapping.entrySet()) {
                if(entry.getValue().hasContext(contextRoot)) {
                    return unbindContextRoot(entry.getKey(), contextRoot);
                }
            }
        }

        return false;
    }

    /**
     * Unbinds a user (virtual) URI.
     *
     * @param userURI  User (virtual) URI to unbind.
     *
     * @return true if succeeded, false otherwise.
     */
    public static boolean unbindVirtualContext(final String userURI) {
        if(webContainer.isVersioningEnabled()) {
            VirtualContext context = contextURIMapping.get(userURI);
            if(context == null) {
                return false;
            } else {
                contextURIMapping.remove(userURI);
                webContainer.getVersioningService().removeContext(context.getMBeanName());
                return context.removeVirtualContext();
            }
        } else {
            return false;
        }
    }
}
