/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 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.deploy;

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

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.management.javaee.J2eeObjectName;
import org.ow2.jonas.webapp.jonasadmin.JonasAdminJmx;

/**
 *
 * @author Patrick Smith
 *         Greg Lapouchnian
 *         Adriana Danes
 */

public class EditDomainDeployAction extends BaseDeployAction {

    static final int indentUnit = 2;
    static final char indentChar = '_';
    /**
     * State corresponding to a cluster having all members running.
     * @see org.ow2.jonas.lib.management.domain.cluster.BaseCluster
     */
    static final String running_cluster = "UP";

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

    public ActionForward executeAction(ActionMapping p_Mapping, ActionForm p_Form
        , HttpServletRequest p_Request, HttpServletResponse p_Response)
        throws IOException, ServletException {

        String serverName = m_WhereAreYou.getCurrentJonasServerName();
        String domainName = m_WhereAreYou.getCurrentDomainName();
        // Form used
        DomainDeployForm oForm = (DomainDeployForm) p_Form;
        try {
            // Store type deployment if exists
            setCurrentJonasDeployment(p_Request);
            // Domain ObjectName
            ObjectName on = J2eeObjectName.J2EEDomain(domainName);

            // Check we are on a master
            boolean isMaster = getBooleanAttribute(on, "master");
            if (!isMaster) {
                Throwable t = new Throwable("Can't do domain deployment because the current server is not a master");
                addGlobalError(t);
                saveErrors(p_Request, m_Errors);
                return (p_Mapping.findForward("Global Error"));
            }
            // Get all targets in the domain: started servers and clusters
            ArrayList alTargets = new ArrayList();
            ArrayList alTargetNames = new ArrayList();
            getTargetServerList(alTargetNames, alTargets, on, serverName);
            // Get deployable files (all files on the local server)
            ArrayList alDeployable = getListDeployableFiles();
            ArrayList alDeployed = getListDeployedFiles();

            // Deploy files
            //ArrayList alDeploy = new ArrayList(alDeployable);

            // Set in form
            oForm.setListDeployable(JonasAdminJmx.getDeployed(alDeployable));
            oForm.setListDeployed(alDeployed);
            oForm.setListTargets(alTargets);
            oForm.setListTargetNames(alTargetNames);
            //oForm.setListDeploy(alDeploy);
            //oForm.setDeploy(Jlists.getString(alDeploy, Jlists.SEPARATOR));
            oForm.setIsConfigurable(isConfigurable());

        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(p_Request, m_Errors);
            return (p_Mapping.findForward("Global Error"));
        }
        // Forward to the jsp.
        return (p_Mapping.findForward(getForwardEdit()));
    }

    /**
     *
     * @param targetNames List of target names - output parameter
     * @param targetONs List of target ONs - output parameter
     * @param domainOn domain ObjectName
     * @param serverName the currently managed server
     * @return total number of target servers and clusters
     * @throws MalformedObjectNameException Couldn't determine the target ObjectNames
     */
    int getTargetServerList(ArrayList targetNames, ArrayList targetONs, final ObjectName domainOn, final String serverName)
        throws MalformedObjectNameException {
        String domainName = domainOn.getKeyProperty("name");
        String[] startedServers = (String[]) JonasManagementRepr.getAttribute(domainOn, "startedServers", serverName);

        for (int i = 0; i < startedServers.length; i++) {
            String startedServer = ObjectName.getInstance(startedServers[i]).getKeyProperty("name");
            targetNames.add(startedServer);
            targetONs.add(startedServers[i]);
        }

        String[] clusters = (String []) JonasManagementRepr.getAttribute(domainOn, "clusters", serverName);
        for (int i = 0; i < clusters.length; i++) {
            ObjectName clOn = ObjectName.getInstance(clusters[i]);
            String state = getStringAttribute(clOn, "State");
            if (!state.equals(running_cluster)) {
                break;
            }
            String clusterName =  clOn.getKeyProperty("name");
            if (!clusterName.equals(domainName)) {
                targetNames.add(clusterName);
                targetONs.add(clusters[i]);
            }
        }

        return startedServers.length + clusters.length;
    }
}
