/**
 * 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 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.tomcat6.versioning;

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

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

/**
 * 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 List<String> nonVersionedContexts = new ArrayList<String>();

    /**
     * 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 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 Request req, final VersionedPathBean vpb)
            throws IOException {
        final String decodedURIString = decodedURI.toString();
        logger.debug("Starting getContextURI with decodedURI {0} and request {1}", decodedURIString, req);

        if (webContainer.isVersioningEnabled()) {
            VirtualContext vctx = null;
            for (Map.Entry<String, VirtualContext> entry : contextURIMapping.entrySet()) {
                final String key = entry.getKey();
                final String keyWithEndingSlash;
                if (key.length() > 1) {
                    // The virtual context / has an ending slash, others don't
                    keyWithEndingSlash = key + '/';
                } else {
                    keyWithEndingSlash = key;
                }
                if (decodedURIString.equals(keyWithEndingSlash)) {
                    vctx = entry.getValue();
                    break;
                } else if (decodedURIString.startsWith(key)) {
                    if (vctx == null) {
                        vctx = entry.getValue();
                    } else if (entry.getValue().userURI.length() > vctx.userURI.length()) {
                        vctx = entry.getValue();
                    }
                }
            }

            if (vctx != null) {
                final String userURIWithEndingSlash;
                if (vctx.userURI.length() > 1) {
                    // The virtual context / has an ending slash, others don't
                    userURIWithEndingSlash = vctx.userURI + '/';
                } else {
                    userURIWithEndingSlash = vctx.userURI;
                }

                if (!decodedURIString.startsWith(userURIWithEndingSlash)) {
                    logger.debug("Final slash missing for decodedURI {0} and request {1}", decodedURIString, req);
                    return decodedURI;
                }

                for (String context : nonVersionedContexts) {
                    if (decodedURIString.startsWith(context) && context.length() > userURIWithEndingSlash.length()) {
                        logger.debug("Found non-versioned context {0} for decodedURI {1} and request {2}", context,
                            decodedURIString, req);
                        return decodedURI;
                    }
                }

                String versionedPath = vctx.findContext(req);
                StringBuffer versionedURI = new StringBuffer();
                if (versionedPath == null) {
                    logger.debug("No version found on virtual context {0} for request {1}", vctx.userURI, req);

                    versionedURI.append(vctx.userURI);
                    versionedURI.append("-invalid-version/");
                } else {
                    logger.debug("Found versioned context {0} on virtual context {1} for request {2}", versionedPath,
                        vctx.userURI, req);

                    vpb.setUserPath(vctx.userURI);
                    vpb.setVersionedPath(versionedPath);
                    versionedURI.append(versionedPath);
                    versionedURI.append('/');

                    if (decodedURIString.length() > userURIWithEndingSlash.length()) {
                        versionedURI.append(decodedURIString.substring(userURIWithEndingSlash.length()));
                    }
                }
                logger.debug("Setting versionedURI to {0} for decodedURI {1} and request {2}", versionedURI, decodedURIString,
                    req);

                MessageBytes contextURI = MessageBytes.newInstance();
                contextURI.setChars(versionedURI.toString().toCharArray(), 0, versionedURI.length());
                return contextURI;
            }
        }

        logger.debug("No virtual context for decodedURI {0} and request {1}", decodedURIString, req);
        return decodedURI;
    }

    /**
     * Adds a non-versioned context root.
     * @param context Context root.
     */
    public static void addNonVersionedContext(String context) {
        if (!context.startsWith("/")) {
            context += "/" + context;
        }
        nonVersionedContexts.add(context);
    }

    /**
     * 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);
            } 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;
        }
    }

    /**
     * Remove a non-versioned context root.
     * @param context Context root.
     */
    public static void removeNonVersionedContext(String context) {
        if (!context.startsWith("/")) {
            context += "/" + context;
        }
        nonVersionedContexts.remove(context);
    }

    /**
     * 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);
                return context.removeVirtualContext();
            }
        } else {
            return false;
        }
    }
}
