/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2005 Bull S.A.
 * Contact: jonas-team@objectweb.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 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.objectweb.jonas.jonasadmin.test.logging;

import java.io.IOException;

import org.xml.sax.SAXException;

import com.meterware.httpunit.SubmitButton;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebResponse;

/**
 * Class to use logging pages
 * @author Paul Kemler
 *
 */
public class LoggerUtils {

    /**
     * NAME of FRAME content
     */
    protected static final String FRAME_CONTENT = "content";

    /**
     * NAME of FRAME tree
     */
    protected static final String FRAME_TREE = "tree";

    /**
     * URL of the logger list
     */
    private static final String URL_JONASADMIN_LOGGING = "ListLoggers.do";

    /**
     * URL for creating a logger
     */
    private static final String URL_JONASADMIN_CREATE_LOGGER = "EditCatalinaAccessLogger.do?action=create";

    /**
     * URL for modifying an engine logger
     */
    private static final String URL_JONASADMIN_MODIFY_ENGINE_LOGGER = "EditCatalinaAccessLogger.do?select=jonas%3Atype%3DValve%2Cname%3DAccessLogValve";

    /**
     * URL for modifying a host logger
     */
    private static final String URL_JONASADMIN_MODIFY_HOST_LOGGER = "EditCatalinaAccessLogger.do?select=jonas%3Atype%3DValve%2Cname%3DAccessLogValve%2Chost";

    /**
     * Get logger page
     * @param wc logged to jonasAdmin
     * @return content frame of logger page
     * @throws SAXException if an error occurs when link is matched or clicked
     * @throws IOException if an error occurs when link is clicked
     */
    public static WebResponse getLoggerPage(WebConversation wc) throws SAXException, IOException {
        // Go to logger page (ListLoggers.do)
        WebResponse wr;
        WebLink link;

        wr = wc.getFrameContents(FRAME_TREE);

        link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_LOGGING);
        if (link != null) {
            link.click();
        } else {
            throw new IllegalThreadStateException("The link " + URL_JONASADMIN_LOGGING + " is not found. ");
        }

        wr = wc.getFrameContents(FRAME_CONTENT);
        return wr;
    }

    /**
     * Create a new engine logger
     * @param wc logged to jonasAdmin
     * @throws Exception if an error occurs
     */
    public static void createNewEngineLogger(WebConversation wc) throws Exception {
        createNewLogger(wc, null, null);
    }

    /**
     * Create a new host logger: container type = Host and container name = localhost
     * @param wc logged to jonasAdmin
     * @throws Exception if an error occurs
     */
    public static void createNewHostLogger(WebConversation wc) throws Exception {
        createNewLogger(wc, "Host", "localhost");
    }

    /**
     * Create a new logger
     * @param wc logged to jonasAdmin
     * @throws Exception if an error occurs
     */
    public static void createNewLogger(WebConversation wc, String containerType, String containerName) throws Exception {

        WebResponse wr = null;
        WebLink link = null;
        WebForm form = null;

        String objectName;
        String directory;
        String action;
        String save;
        String resolveHosts;
        String rotatable;
        String suffix;
        String prefix;
        String pattern;

        wr = getLoggerPage(wc);

        // Verify if 'Access log valve engine' has yet been created
        if (wr.getText().indexOf("AccessLogValve,seq") == -1) {
            // Go to EditCatalinaAccessLogger.do?action=create
            link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_CREATE_LOGGER);
            if (link != null) {
                link.click();
            } else {
                throw new IllegalThreadStateException("The link " + URL_JONASADMIN_CREATE_LOGGER + " is not found. ");
            }
            wr = wc.getFrameContents(FRAME_CONTENT);

            form = wr.getForms()[0];

            objectName = form.getParameterValue("objectName");
            directory = form.getParameterValue("directory");
            action = form.getParameterValue("action");
            save = form.getParameterValue("save");
            resolveHosts = form.getParameterValue("resolveHosts");
            rotatable = form.getParameterValue("rotatable");
            suffix = form.getParameterValue("suffix");
            prefix = form.getParameterValue("prefix");
            pattern = form.getParameterValue("pattern");
            if (containerType == null) {
                containerName = form.getParameterValue("containerName");
                containerType = form.getParameterValue("containerType");
            }

            createNewLogger(form, objectName, directory, action, save, resolveHosts, rotatable, suffix, prefix,
                    pattern, containerName, containerType);

        }
    }

    /**
     * Create a new logger
     * @param form Web Form to create logger
     * @param objectName a string
     * @param directory a string
     * @param action a string
     * @param save a string
     * @param resolveHosts a string
     * @param rotatable a string
     * @param suffix a string
     * @param prefix a string
     * @param pattern a string
     * @param containerName a string
     * @param containerType "Engine" or "Host"
     * @throws Exception if an error occurs when the button is clicked
     */
    public static void createNewLogger(WebForm form, String objectName, String directory, String action, String save,
            String resolveHosts, String rotatable, String suffix, String prefix, String pattern, String containerName,
            String containerType) throws Exception {

        SubmitButton button = null;

        form.setParameter("objectName", objectName);
        form.setParameter("directory", directory);
        form.setParameter("action", action);
        form.setParameter("save", save);
        form.setParameter("resolveHosts", resolveHosts);
        form.setParameter("rotatable", rotatable);
        form.setParameter("suffix", suffix);
        form.setParameter("prefix", prefix);
        form.setParameter("pattern", pattern);
        form.setParameter("containerName", containerName);
        form.setParameter("containerType", containerType);

        button = form.getSubmitButton("btn_apply");
        button.click();
    }

    /**
     * Delete logger
     * @param wc logged to jonasAdmin
     * @param host
     * @throws Exception if an error occurs
     */
    public static void deleteLogger(WebConversation wc, String host) throws Exception {
        WebResponse wr = null;
        WebForm form = null;
        WebLink link = null;
        SubmitButton button = null;

        String action = "";

        wr = getLoggerPage(wc);

        // Select logger to remove
        form = wr.getForms()[0];
        action = form.getParameterValue("action");
        if (host == null) {
            form.setCheckbox("selectedItemsArray", "jonas:type=Valve,name=AccessLogValve", true);
        } else {
            form.setCheckbox("selectedItemsArray", "jonas:type=Valve,name=AccessLogValve,host=" + host, true);
        }

        // Choose remove action
        link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, "remove");
        if (link != null) {
            link.click();
        } else {
            throw new IllegalThreadStateException("The link " + "remove" + " is not found. ");
        }
        wr = wc.getFrameContents(FRAME_CONTENT);

        // Confirm
        form = wr.getForms()[0];
        button = form.getSubmitButton("btnSubmit");
        button.click();

    }

    /**
     * Modify a logger
     * @param wc logged to jonasAdmin
     * @param host null if container type is "engine" else container name
     * @param directory a string
     * @param resolveHosts "true" or "false"
     * @param rotatable "true" or "false"
     * @param suffix a string
     * @param prefix a string
     * @param pattern a string
     * @throws Exception if an error occurs
     */
    public static void modifyLogger(WebConversation wc, String host, String directory, String resolveHosts,
            String rotatable, String suffix, String prefix, String pattern) throws Exception {

        WebResponse wr = null;
        WebForm form = null;
        WebLink link = null;
        SubmitButton button = null;

        String objectName = null;
        String action = null;
        String save = null;

        wr = getLoggerPage(wc);

        // Get form
        if (host == null) {
            link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_MODIFY_ENGINE_LOGGER);
            if (link.getURLString().endsWith(URL_JONASADMIN_MODIFY_ENGINE_LOGGER)
                    || link.getURLString().indexOf("%2Cseq%3D") != -1) {
                if (link != null) {
                    link.click();
                } else {
                    throw new IllegalThreadStateException("The link " + URL_JONASADMIN_MODIFY_ENGINE_LOGGER
                            + " is not found. ");
                }
                wr = wc.getFrameContents(FRAME_CONTENT);
            } else {
                throw new IllegalThreadStateException("There is not " + URL_JONASADMIN_MODIFY_ENGINE_LOGGER + " link. ");
            }
        } else {
            link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_MODIFY_HOST_LOGGER);
            if (link != null) {
                link.click();
            } else {
                throw new IllegalThreadStateException("The link " + URL_JONASADMIN_MODIFY_HOST_LOGGER
                        + " is not found. ");
            }

            wr = wc.getFrameContents(FRAME_CONTENT);
        }
        form = wr.getForms()[0];

        // get hidden params
        objectName = form.getParameterValue("objectName");
        action = form.getParameterValue("action");
        save = form.getParameterValue("save");

        form.setParameter("objectName", objectName);
        form.setParameter("action", action);
        form.setParameter("save", save);
        form.setParameter("directory", directory);
        form.setParameter("resolveHosts", resolveHosts);
        form.setParameter("rotatable", rotatable);
        form.setParameter("suffix", suffix);
        form.setParameter("prefix", prefix);
        form.setParameter("pattern", pattern);

        button = form.getSubmitButton("btn_apply");
        button.click();
    }

}
