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

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.management.ObjectName;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.management.extensions.base.mbean.CatalinaObjectName;
import org.ow2.jonas.webapp.jonasadmin.JonasAdminJmx;
import org.ow2.jonas.webapp.jonasadmin.WhereAreYou;
import org.ow2.jonas.webapp.jonasadmin.service.container.WebAppItem;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * @author Michel-Ange ANTON
 * @author Adriana Danes
 */

public class EditCatalinaAccessLoggerAction extends BaseLoggerAction {

// --------------------------------------------------------- Public Methods

    public ActionForward executeAction(ActionMapping pMapping, ActionForm pForm
        , HttpServletRequest pRequest, HttpServletResponse pResponse)
        throws IOException, ServletException {

        // Parameters
        String sAction = pRequest.getParameter("action");
        if (sAction == null) {
            sAction = "edit";
        }
        String sObjectName = pRequest.getParameter("select");
        // Form used
        CatalinaAccessLogValveForm oForm = null;
        if (("create".equals(sAction) == true) || (sObjectName != null)) {
            oForm = new CatalinaAccessLogValveForm();
            m_Session.setAttribute("catalinaAccessLoggerForm", oForm);
            oForm.reset(pMapping, pRequest);
            oForm.setObjectName(sObjectName);
        } else {
            oForm = (CatalinaAccessLogValveForm) m_Session.getAttribute("catalinaAccessLoggerForm");
        }
        oForm.setAction(sAction);

        // Current JOnAS server
        String serverName = m_WhereAreYou.getCurrentJonasServerName();

        // Polulate
        try {
            if (oForm.getObjectName() != null) {
                // Get the access logger
                ObjectName on = new ObjectName(oForm.getObjectName());
                String loggerContainerType = null; // needed for mgmt tree node name
                String loggerContainerName = null; // needed for mgmt tree node name
                // Populate
                oForm.setObjectName(on.toString());
                oForm.setDirectory(getStringAttribute(on, "directory"));
                oForm.setPattern(getStringAttribute(on, "pattern"));
                oForm.setPrefix(getStringAttribute(on, "prefix"));
                oForm.setResolveHosts(getBooleanAttribute(on, "resolveHosts"));
                oForm.setRotatable(getBooleanAttribute(on, "rotatable"));
                oForm.setSuffix(getStringAttribute(on, "suffix"));
                ObjectName onContainer = (ObjectName) JonasManagementRepr.getAttribute(on, "containerName", serverName);
                if (onContainer.getKeyProperty("j2eeType") != null) {
                    if (onContainer.getKeyProperty("j2eeType").equals("WebModule")) {
                        // The container is a Web application (Context element in Tomcat)
                        oForm.setContainerType(m_Resources.getMessage("label.loggers.container.context"));
                        String webContainerName = WebAppItem.extractLabelPathContext(
                                onContainer.getKeyProperty("name")
                                , m_WhereAreYou.getCurrentCatalinaDefaultHostName());
                        oForm.setContainerName(webContainerName);
                        oForm.setContainerObjectName(onContainer.toString());
                        loggerContainerType = LoggerItem.LOGGER_CATALINA_ACCESS_CONTEXT;
                        loggerContainerName = on.getKeyProperty("path");
                    }
                } else if (onContainer.getKeyProperty("type") != null) {
                    if (onContainer.getKeyProperty("type").equals("Engine")) {
                        oForm.setContainerType(m_Resources.getMessage("label.loggers.container.engine"));
                        oForm.setContainerName(m_Resources.getMessage("label.loggers.container.engine.name"));
                        loggerContainerType = LoggerItem.LOGGER_CATALINA_ACCESS_ENGINE;
                        loggerContainerName = oForm.getContainerName();
                    } else if (onContainer.getKeyProperty("type").equals("Host")) {
                        oForm.setContainerType(m_Resources.getMessage("label.loggers.container.host"));
                        oForm.setContainerName(onContainer.getKeyProperty("host"));
                        loggerContainerType = LoggerItem.LOGGER_CATALINA_ACCESS_HOST;
                        loggerContainerName = on.getKeyProperty("host");
                    }
                }
                // Force the node selected in tree
                m_WhereAreYou.selectNameNode(getTreeBranchName(DEPTH_SERVER)
                    + WhereAreYou.NODE_SEPARATOR
                    + "logging"
                    + WhereAreYou.NODE_SEPARATOR
                    + loggerContainerType
                    + WhereAreYou.NODE_SEPARATOR
                    + loggerContainerName, true);
            } else {
                oForm.setCatalinaDomainName(m_WhereAreYou.getCurrentCatalinaDomainName());
                ObjectName hostsOn = CatalinaObjectName.catalinaHosts(m_WhereAreYou.getCurrentCatalinaDomainName());
                Iterator hosts = JonasAdminJmx.getListMbean(hostsOn, serverName).iterator();
                ArrayList hostNames = new ArrayList();
                for (; hosts.hasNext();) {
                    hostNames.add(((ObjectName) hosts.next()).getKeyProperty("host"));
                }
                String[] allNames = new String[hostNames.size() + 1];
                allNames[0] = "no name required for Engine";
                for (int i=1; i < allNames.length; i++) {
                    allNames[i] = (String) hostNames.get(i-1);
                }
                oForm.setContainerNames(allNames);
            }
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(pRequest, m_Errors);
            return (pMapping.findForward("Global Error"));
        }
        // Forward to the jsp.
        return (pMapping.findForward("Catalina Access Logger"));
    }

}
