/*
 * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.kernel.security;

import com.arsdigita.initializer.InitializationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;

/**
 * <p>Parses a login <code>Configuration</code> from an
 * <code>Initializer</code> entry.</p>
 *
 * @author Sameer Ajmani
 * @since ACS 4.5
 **/
public class LoginConfig extends Configuration {

    public static final String versionId = "$Id: //core-platform/dev/src/com/arsdigita/kernel/security/LoginConfig.java#7 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";
    /** Maps application names to <code>AppConfigurationEntry[]</code>. **/
    private Map m_appConfigs = new HashMap();

    /**
     * <p>Creates a new login configuration from the given list
     * (<code>loginConfig</code>).  Grammar: </p>
     *
     * <dl>
     * <dt><i>loginConfig</i></dt>
     * <dd>{ appName1, moduleList1 [, ... , appNameN, moduleListN ] }</dd>
     *
     * <dt><i>appName</i></dt>
     * <dd>String</dd>
     *
     * <dt><i>moduleList</i></dt>
     * <dd>{ moduleConf1 [, ..., moduleConfN ] }</dd>
     *
     * <dt><i>moduleConf</i></dt>
     * <dd>{ moduleName, controlFlag [, option1, ..., optionN ] }</dd>
     *
     * <dt><i>moduleName</i></dt>
     * <dd>String</dd>
     *
     * <dt><i>controlFlag</i></dt>
     * <dd>"required"</dd>
     * <dd>"requisite"</dd>
     * <dd>"sufficient"</dd>
     * <dd>"optional"</dd>
     *
     * <dt><i>option</i></dt>
     * <dd>"key=value"</dd>
     * </dl>
     *
     * <p>Example:</p>
     *
     * <pre>
     * loginConfig = {
     *   "Request", {
     *     {"com.arsdigita.kernel.security.CredentialLoginModule", "requisite",
     *      "debug=true"}
     *   },
     *   "Register", {
     *     {"com.arsdigita.kernel.security.LocalLoginModule", "requisite"},
     *     {"com.arsdigita.kernel.security.UserIDLoginModule", "requisite"},
     *     {"com.arsdigita.kernel.security.CredentialLoginModule", "optional"}
     *   }
     * };
     * </pre>
     *
     * @throws InitializationException if there is a parsing error.
     **/
    public LoginConfig(List list) throws InitializationException {
        Iterator iter = list.iterator();
        while (iter.hasNext()) {
            String name = getString(iter, "application name");
            List entries = getList(iter, "module configs");
            addAppConfig(name, entries);
        }
    }

    private void addAppConfig(String name, List entries)
        throws InitializationException {
        AppConfigurationEntry[] array =
            new AppConfigurationEntry[entries.size()];
        Iterator iter = entries.iterator();
        for (int i = 0; i < array.length; i++) {
            List entry = getList(iter, "{module, flag, options...}");
            array[i] = loadAppConfigEntry(entry);
        }
        m_appConfigs.put(name, array);
    }

    private AppConfigurationEntry loadAppConfigEntry(List list)
        throws InitializationException {
        Iterator iter = list.iterator();
        String name = getString(iter, "module class name");
        AppConfigurationEntry.LoginModuleControlFlag flag
            = getFlag(getString(iter, "control flag"));
        Map options = new HashMap();
        while (iter.hasNext()) {
            addOption(iter, options);
        }
        return new AppConfigurationEntry(name, flag, options);
    }

    private AppConfigurationEntry.LoginModuleControlFlag
        getFlag(String flag) throws InitializationException {
        if (flag.equalsIgnoreCase("requisite")) {
            return AppConfigurationEntry.LoginModuleControlFlag.REQUISITE;
        }
        if (flag.equalsIgnoreCase("required")) {
            return AppConfigurationEntry.LoginModuleControlFlag.REQUIRED;
        }
        if (flag.equalsIgnoreCase("sufficient")) {
            return AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT;
        }
        if (flag.equalsIgnoreCase("optional")) {
            return AppConfigurationEntry.LoginModuleControlFlag.OPTIONAL;
        }
        throw new InitializationException
            ("Control flag must be one of \"required\", "
             +"\"requisite\", \"sufficient\", or \"optional\", "
             +"but got: \""+flag+"\"");
    }

    private void addOption(Iterator iter, Map map)
        throws InitializationException {
        String option = getString(iter, "option");
        int index = option.indexOf('=');
        if (index == -1) {
            throw new InitializationException
                ("Option must be \"key=value\", but got: \""
                 +option+"\"");
        }
        String key = option.substring(0, index);
        String value = option.substring(index+1);
        map.put(key, value);
    }

    private String getString(Iterator iter, String name)
        throws InitializationException {
        Object temp = getObject(iter, name);
        if (!(temp instanceof String)) {
            throw new InitializationException
                ("Expected String "+name
                 +", but got: \""+temp+"\"");
        }
        return (String)temp;
    }

    private List getList(Iterator iter, String name)
        throws InitializationException {
        Object temp = getObject(iter, name);
        if (!(temp instanceof List)) {
            throw new InitializationException
                ("Expected List "+name
                 +", but got: \""+temp+"\"");
        }
        return (List)temp;
    }

    private Object getObject(Iterator iter, String name)
        throws InitializationException {
        if (!iter.hasNext()) {
            throw new InitializationException
                ("Missing "+name);
        }
        return iter.next();
    }

    // overrides Configuration
    public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
        return (AppConfigurationEntry[])m_appConfigs.get(name);
    }

    // overrides Configuration
    public void refresh() {
        // do nothing
    }

    /**
     * Add an application configuration to this Configuration.
     * Package-private.
     **/
    void addAppConfig(String name, AppConfigurationEntry[] entries) {
        m_appConfigs.put(name, entries);
    }
}
