/*

 ============================================================================
                   The Apache Software License, Version 1.1
 ============================================================================

 Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.

 Redistribution and use in source and binary forms, with or without modifica-
 tion, are permitted provided that the following conditions are met:

 1. Redistributions of  source code must  retain the above copyright  notice,
    this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. The end-user documentation included with the redistribution, if any, must
    include  the following  acknowledgment:  "This product includes  software
    developed  by the  Apache Software Foundation  (http://www.apache.org/)."
    Alternately, this  acknowledgment may  appear in the software itself,  if
    and wherever such third-party acknowledgments normally appear.

 4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
    used to  endorse or promote  products derived from  this software without
    prior written permission. For written permission, please contact
    apache@apache.org.

 5. Products  derived from this software may not  be called "Apache", nor may
    "Apache" appear  in their name,  without prior written permission  of the
    Apache Software Foundation.

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
 APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
 INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
 DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
 OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
 ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
 (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 This software  consists of voluntary contributions made  by many individuals
 on  behalf of the Apache Software  Foundation and was  originally created by
 Stefano Mazzocchi  <stefano@apache.org>. For more  information on the Apache
 Software Foundation, please see <http://www.apache.org/>.

*/
package org.apache.cocoon.webapps.authentication.components;

import java.io.IOException;
import java.util.*;

import org.apache.excalibur.source.SourceParameters;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;

import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.webapps.session.context.SessionContext;
import org.apache.cocoon.webapps.session.connector.*;
import org.xml.sax.SAXException;

/**
 * The authentication Handler.
 *
 * @author <a href="mailto:cziegeler@s-und-n.de">Carsten Ziegeler</a>
 * @version CVS $Id: Handler.java,v 1.2 2002/04/19 11:02:58 cziegeler Exp $
*/
public final class Handler
implements java.io.Serializable {

    /** The unique name of the handler */
    private final String name;

    /** The redirect-to URI */
    private String redirectURI;

    /** The redirect parameters */
    private SourceParameters redirectParameters;

    /** The authentication resource */
    private Resource authenticationResource;

    /** The load resource (optional) */
    private Resource loadResource;

    /** The save resource (optional) */
    private Resource saveResource;

    /** The ApplicationHandler */
    private Map applications = new Hashtable(3, 2);

    /** The load-users resource */
    private Resource loadUsersResource;

    /** The load-roles resource */
    private Resource loadRolesResource;

    /** The new-user resource */
    private Resource newUserResource;

    /** The new-role resource */
    private Resource newRoleResource;

    /** The delete-role resource */
    private Resource deleteRoleResource;

    /** The delete-user resource */
    private Resource deleteUserResource;

    /** The change-user resource */
    private Resource changeUserResource;

    /** The name of the context attribute, where isLoaded is stored */
    private final String attributeName;

    /** The handler contexts */
    private List handlerContexts = new ArrayList(2);

    /**
     * Create a new handler object.
     */
    public Handler(String name) {
        this.name = name;
        this.attributeName = "authentication_H_" + this.name;
    }

    /**
     * Configure
     */
    public void configure(SourceResolver resolver,
                          Request        request,
                          Configuration  conf)
    throws ProcessingException, SAXException, IOException, ConfigurationException {
        // get login (required)
        Configuration child = conf.getChild("redirect-to", false);
        if (child == null)
            throw new ConfigurationException("Handler '"+this.name+"' needs a redirect-to URI.");
        this.redirectURI = child.getAttribute("uri");
        if ( this.redirectURI.startsWith("cocoon://") ) {
            this.redirectURI = this.redirectURI.substring("cocoon://".length()).trim();
            this.redirectURI = request.getContextPath()+"/"+this.redirectURI;
        } else if ( this.redirectURI.startsWith("cocoon:/") ) {
            this.redirectURI = this.redirectURI.substring("cocoon:/".length()).trim();
        }

        this.redirectParameters = SourceParameters.create(child);

        // get load resource (required)
        child = conf.getChild("authentication", false);
        if (child == null)
            throw new ConfigurationException("Handler '"+this.name+"' needs authentication configuration");
        this.authenticationResource = new Resource(resolver, child.getAttribute("uri"));
        this.authenticationResource.setResourceParameters(SourceParameters.create(child));

        // get load resource (optional)
        child = conf.getChild("load", false);
        if (child != null) {
            this.loadResource = new Resource(resolver, child.getAttribute("uri"));
            this.loadResource.setResourceParameters(SourceParameters.create(child));
        }

        // get save resource (optional)
        child = conf.getChild("save", false);
        if (child != null) {
            this.saveResource = new Resource(resolver, child.getAttribute("uri"));
            this.saveResource.setResourceParameters(SourceParameters.create(child));
        }

        // get load-users resource (optional)
        child = conf.getChild("load-users", false);
        if (child != null) {
            this.loadUsersResource = new Resource(resolver, child.getAttribute("uri"));
            this.loadUsersResource.setResourceParameters(SourceParameters.create(child));
        }

        // get load-roles resource (optional)
        child = conf.getChild("load-roles", false);
        if (child != null) {
            this.loadRolesResource = new Resource(resolver, child.getAttribute("uri"));
            this.loadRolesResource.setResourceParameters(SourceParameters.create(child));
        }

        // get new user resource (optional)
        child = conf.getChild("new-user", false);
        if (child != null) {
            this.newUserResource = new Resource(resolver, child.getAttribute("uri"));
            this.newUserResource.setResourceParameters(SourceParameters.create(child));
        }

        // get new role resource (optional)
        child = conf.getChild("new-role", false);
        if (child != null) {
            this.newRoleResource = new Resource(resolver, child.getAttribute("uri"));
            this.newRoleResource.setResourceParameters(SourceParameters.create(child));
        }

        // get delete user resource (optional)
        child = conf.getChild("delete-user", false);
        if (child != null) {
            this.deleteUserResource = new Resource(resolver, child.getAttribute("uri"));
            this.deleteUserResource.setResourceParameters(SourceParameters.create(child));
        }

        // get delete role resource (optional)
        child = conf.getChild("delete-role", false);
        if (child != null) {
            this.deleteRoleResource = new Resource(resolver, child.getAttribute("uri"));
            this.deleteRoleResource.setResourceParameters(SourceParameters.create(child));
        }

        // get change user resource (optional)
        child = conf.getChild("change-user", false);
        if (child != null) {
            this.changeUserResource = new Resource(resolver, child.getAttribute("uri"));
            this.changeUserResource.setResourceParameters(SourceParameters.create(child));
        }

        // And now: Applications
        child = conf.getChild("applications", false);
        if (child != null) {
            Configuration[] appConfs = child.getChildren("application");
            Configuration appconf;

            if (appConfs != null) {
                for(int i = 0; i < appConfs.length; i++) {
                    appconf = appConfs[i];

                    // get name
                    String appName = appconf.getAttribute("name");

                    // test if handler is unique
                    if (this.applications.get(appName) != null) {
                        throw new ConfigurationException("Application names must be unique: " + appName);
                    }

                    // create handler
                    ApplicationHandler apphandler = new ApplicationHandler(this, appName);

                    // store handler
                    this.applications.put(appName, apphandler);

                    // configure
                    apphandler.configure(resolver, appconf);
                }
            }
        }

    }


    /**
     * Get the handler name.
     */
    public String getName() { return name; }

    /**
     * Get the redirect URI
     */
    public String getRedirectURI() {
        return this.redirectURI;
    }

    /**
     * Get the redirect parameters
     */
    public SourceParameters getRedirectParameters() {
        return this.redirectParameters;
    }

    /**
     * Get the authentication resource
     */
    public Resource getAuthenticationResource() {
        return this.authenticationResource;
    }

    /**
     * Get the load users resource
     */
    public Resource getLoadUsersResource() { return loadUsersResource; }

    /**
     * Get the load roles resource
     */
    public Resource getLoadRolesResource() { return loadRolesResource; }

    /**
     * Get the new user resource
     */
    public Resource getNewUserResource() { return this.newUserResource; }

    /**
     * Get the new role resource
     */
    public Resource getNewRoleResource() { return this.newRoleResource; }

    /** Get the delete user resource */
    public Resource getDeleteUserResource() { return this.deleteUserResource; }

    /** Get the delete role resource */
    public Resource getDeleteRoleResource() { return this.deleteRoleResource; }

    /** Get the change user resource */
    public Resource getChangeUserResource() { return this.changeUserResource; }

    /** Get the save resource */
    public Resource getSaveResource() { return this.saveResource; }

    /** Get the save resource */
    public Resource getLoadResource() { return this.loadResource; }

    /**
     * Get the applications map
     */
    public Map getApplications() { return applications; }

    public void setApplicationsLoaded(SessionContext context, boolean value)
    throws ProcessingException {
        Boolean bool = new Boolean(value);
        context.setAttribute(this.attributeName, bool);
    }

    public boolean getApplicationsLoaded(SessionContext context)
    throws ProcessingException {
        if (this.applications.isEmpty() == true) {
            return true;
        } else {
            boolean result = false;
            Boolean bool = (Boolean)context.getAttribute(this.attributeName);
            if (bool != null) result = bool.booleanValue();
            return result;
        }
    }

    /**
     * Add a handler context
     */
    public void addHandlerContext(SessionContext context) {
        this.handlerContexts.add( context );
    }

    /**
     * Get handler contexts
     */
    public List getHandlerContexts() {
        return this.handlerContexts;
    }

    /**
     * Clear handler contexts
     */
    public void clearHandlerContexts() {
        this.handlerContexts.clear();
    }

    /**
     * toString()
     */
    public String toString() {
        return "authentication-Handler " + this.name;
    }
}
