/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 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 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.objectweb.jonas.webapp.jonasadmin.domain;

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

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.objectweb.jonas.jmx.J2eeObjectName;
import org.objectweb.jonas.jmx.ManagementReprLoader;
import org.objectweb.jonas.management.cluster.BaseCluster;
import org.objectweb.jonas.management.j2eemanagement.J2EEDomain;
import org.objectweb.jonas.management.monitoring.ClusterDaemonProxy;
import org.objectweb.jonas.management.monitoring.DomainMonitor;
import org.objectweb.jonas.management.monitoring.ServerProxy;
import org.objectweb.jonas.webapp.jonasadmin.JonasBaseAction;
import org.objectweb.jonas.webapp.jonasadmin.common.BeanComparator;

/**
 * Display domain or cluster informations
 * @author Adriana Danes
 * @author S. Ali Tokmen
 */
public class EditDomainAction extends JonasBaseAction {

    /**
     * Compute info about this cluster or domain
     * Populate the DomainForm
     * Eventually call the domain.jsp for display
     */
    public ActionForward executeAction(ActionMapping p_Mapping, ActionForm p_Form
            , HttpServletRequest p_Request, HttpServletResponse p_Response)
    throws IOException, ServletException {

        try {
            DomainForm oForm = (DomainForm) p_Form;
            String domainName = m_WhereAreYou.getCurrentDomainName();
            boolean changeMap;
            Boolean changeMapObj =  ((Boolean) m_Session.getAttribute("mapChanged"));
            if (changeMapObj == null) {
                changeMap = false;
            } else {
                changeMap = changeMapObj.booleanValue();
            }
            String selected = p_Request.getParameter("select");
            if (selected == null) {
                // By default we edit the domain page
                // -- this is necessary for example when creating a cluster in the
                // domain, at the end of the ApplyClusterAction we come back
                // into EdirDomainAction
                // -- maybe this should be treated otherwise ?
                selected = domainName;
            }
            // domain or cluster name
            String name = selected;
            m_Session.setAttribute("currentCluster", name);

            // Support mgmt context switch from a slave to the master
            // (to the administrator server)
            String adminServerName = m_WhereAreYou.getAdminJonasServerName();
            boolean changeManagement = false;
            if (!adminServerName.equals(m_WhereAreYou.getCurrentJonasServerName())) {
                // change management context from a managed server in the domain
                // to the JonasAdmin server
                ManagementReprLoader.loadServerRepr(adminServerName);
                m_WhereAreYou.refreshServers(p_Request, adminServerName);
                // onCurrentServer = m_WhereAreYou.getCurrentJonasServer();
                changeManagement = true;
            }

            // Force the node selected in tree
            m_WhereAreYou.selectNameNode("domain", true);

            if (changeManagement) {
                refreshServerTree(p_Request);
            }
            if (changeMap) {
                //refreshDomainMonitoringTree(p_Request);
                refreshServerTree(p_Request);

                m_WhereAreYou.setTreeToRefresh(true);
                m_Session.setAttribute("mapChanged", new Boolean(false));
            }
            // domain or cluster
            boolean inCluster = false;
            if (domainName.equals(selected)) {
                // this is a domain
                oForm.setType("Domain");
            } else {
                inCluster = true;
                oForm.setType("Cluster");
            }

            // set general properties
            oForm.setName(name);
            oForm.setDomainName(domainName);
            oForm.setCluster(inCluster);
            oForm.setMasterName(adminServerName);
            oForm.setMasterON(J2eeObjectName.J2EEServer(domainName, adminServerName).toString());
            oForm.setMaster(getBooleanAttribute(m_WhereAreYou.getCurrentDomain(), "master"));

            // Get access to the DomainMonitor and domain/cluster management data
            BaseCluster baseCluster = null;
            DomainMonitor dm = J2EEDomain.getInstance().getDomainMonitor();
            if (dm != null) {
                baseCluster = dm.findCluster(name);
                if (baseCluster == null) {
                    throw new RuntimeException("Cannot find cluster " + name);
                }
                ObjectName clOn = ObjectName.getInstance(baseCluster.getObjectName());
                oForm.setClusterType(clOn.getKeyProperty("type"));
                oForm.setDescription(dm.getDescription());

                // Get servers running in this domain (or cluster)
                ArrayList al = new ArrayList();
                for (Iterator it = baseCluster.getServerProxyList().iterator(); it.hasNext();) {
                    ServerProxy proxy = (ServerProxy) it.next();
                    ObjectName on = ObjectName.getInstance(proxy.getJ2eeObjectName());
                    al.add(new ServerItem(on, proxy.getState(), proxy.getClusterDaemonName()));
                }
                Collections.sort(al, new BeanComparator(new String[] {"name"}));
                p_Request.setAttribute("listServers", al);

                // In the domain view, check if a new server detected in order to do refresh
                if ("Domain".equals(oForm.getType())) {
                    int nbServers = al.size();
                    Integer nbServersObj =  ((Integer) m_Session.getAttribute("nbServers"));
                    if (nbServersObj == null) {
                        m_Session.setAttribute("nbServers", new Integer(nbServers));
                    } else {
                        if (nbServers != nbServersObj.intValue()) {
                            // Add the new servers number to the session
                            m_Session.setAttribute("nbServers", new Integer(nbServers));
                            if (nbServers > nbServersObj.intValue()) {
                                // Servers number in the domain increased
                                refreshServerTree(p_Request);
                                m_WhereAreYou.setTreeToRefresh(true);
                            }
                        }
                    }
                }
                if (!inCluster) {
                    // Get clusters in this domain
                    ArrayList clustAl = new ArrayList();
                    for (Iterator it = dm.getTotalClusterList().iterator(); it.hasNext();) {
                        BaseCluster cl = (BaseCluster) it.next();
                        String clusterName = cl.getName();
                        if (!domainName.equals(clusterName)) {
                            ObjectName on = new ObjectName(cl.getObjectName());
                            ServerItem item = new ServerItem(on, cl.getState(), null);
                            item.setName(clusterName);
                            clustAl.add(item);
                        }
                    }
                    Collections.sort(clustAl, new BeanComparator(new String[] {"name"}));
                    p_Request.setAttribute("listClusters", clustAl);

                    // Get cluster daemons
                    ArrayList clustDaemonAl = new ArrayList();
                    for (Iterator it = dm.getClusterDaemonList().iterator(); it.hasNext();) {
                        ClusterDaemonProxy cdp = (ClusterDaemonProxy) it.next();
                        String cdpName = cdp.getName();
                        ObjectName on = new ObjectName(cdp.getObjectName());
                        ServerItem item = new ServerItem(on, cdp.getState(), null);
                        item.setName(cdpName);
                        clustDaemonAl.add(item);
                    }
                    Collections.sort(clustDaemonAl, new BeanComparator(new String[] {"name"}));
                    p_Request.setAttribute("listCdps", clustDaemonAl);
                    // Re-check server states for a more accurate display
                    dm.refreshStates();
                } else {
                    p_Request.setAttribute("listClusters", new ArrayList());
                    p_Request.setAttribute("listCdps", new ArrayList());
                }
            }
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(p_Request, m_Errors);
            return (p_Mapping.findForward("Global Error"));
        }
        // Forward to the jsp.
        return (p_Mapping.findForward("Domain"));

    }

}
