/**
 * 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.clusterd;

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.ow2.jonas.lib.management.domain.DomainMonitor;
import org.ow2.jonas.lib.management.domain.J2EEDomain;
import org.ow2.jonas.lib.management.domain.proxy.server.ServerProxy;
import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.management.extensions.server.ServerItem;
import org.ow2.jonas.lib.util.JonasObjectName;
import org.ow2.jonas.webapp.jonasadmin.JonasBaseAction;
import org.ow2.jonas.webapp.jonasadmin.common.BeanComparator;
import org.ow2.jonas.webapp.jonasadmin.monitoring.DaemonProxyClusterForm;

public class DaemonProxyClusterAction extends JonasBaseAction {

    @Override
    public ActionForward executeAction(final ActionMapping p_Mapping, final ActionForm p_Form,
            final HttpServletRequest p_Request, final HttpServletResponse p_Response) throws IOException, ServletException {
        String isNotMonitoringStr = null;
        String sDomainName = m_WhereAreYou.getCurrentDomainName();
        String serverName = m_WhereAreYou.getAdminJonasServerName();
        DaemonProxyClusterForm oForm = (DaemonProxyClusterForm) p_Form;
        String name = null;
        try {

            // monitoring mode = false
            isNotMonitoringStr = "true";
            name = (String) p_Request.getAttribute("node");
            if (name == null) {
                // that means the request has been forwarded by another
                // and the current cluster daemon name attribute has already
                // been set
                name = m_WhereAreYou.getCurrentClusterDaemonName();
            }
            if (name == null) {
                // requested by using the parameter attribute
                name = p_Request.getParameter("node");
            }
            ObjectName on = JonasObjectName.clusterDaemonProxy(sDomainName, name);
            m_WhereAreYou.setCurrentClusterDaemon(on);
            m_WhereAreYou.setCurrentClusterDaemonName(name);
            oForm.setName((String) JonasManagementRepr.getAttribute(on, "Name", serverName));
            oForm.setState((String) JonasManagementRepr.getAttribute(on, "State", serverName));
            oForm.setConServer((ArrayList) JonasManagementRepr.getAttribute(on, "ControlledServersNames", serverName));
            ArrayList<String> srvList = oForm.getConServer();

            if (srvList == null) {
                throw new Throwable("Can't get management information for cluster daemon " + name + ". Please check the domain configuration.");
            }
            // getting dynamic remote host monitoring infos
            DomainMonitor dm = J2EEDomain.getInstance().getDomainMonitor();
            // the array list to contain the server list
            ArrayList al = new ArrayList();
            // are all the servers already started ?
            boolean allStarted = true;
            // let know if no server is running
            boolean noneStarted = true;
            // Get requested cluster daemon administered Jonas servers...
            for (Iterator it = dm.getServerList().iterator(); it.hasNext();) {
                ServerProxy proxy = (ServerProxy) it.next();
                if (srvList.contains(proxy.getName())) {
                    // if the server is in the clusterd.xml but not in the
                    // domain.xml
                    if (m_WhereAreYou.isSrvRemovedFromClusterd(name, proxy.getName())) {
                        // the server is no more affected to current clusterd
                        proxy.setClusterdaemon(null);

                    } else {
                        // the server is in clusterd.xml
                        if (proxy.getClusterDaemonName() == null) {
                            // the server is not in domain.xml file
                            proxy.setClusterdaemon(dm.findClusterDaemonProxy(name));
                        }

                    }

                }
                if (proxy.getClusterDaemonName() != null) {
                    if (proxy.getClusterDaemonName().equals(name)) {
                        ObjectName myOn = ObjectName.getInstance(proxy.getJ2eeObjectName());
                        al.add(new ServerItem(myOn, proxy.getState(), proxy.getClusterDaemonName(), srvList.contains(proxy
                                .getName())));
                        // no server is started we want to disable the startAll
                        // operation in the jsp
                        if (noneStarted) {
                            // None is stared if none is RUNNING nor STANDBY.
                            noneStarted = !"STANDBY".equals(proxy.getState()) && !"RUNNING".equals(proxy.getState());
                        }
                        // all server are started if alrr server are running or
                        // STANDBY.
                        allStarted = (allStarted && (proxy.getState().equals("RUNNING") || "STANDBY".equals(proxy.getState())));
                    }
                }
            }
            Collections.sort(al, new BeanComparator(new String[] {"name"}));
            // if a problem has happened while getting jmxUrl then :
            // forward the response to with default values
            p_Request.setAttribute("listServers", al);
            p_Request.setAttribute("allStarted", allStarted);
            p_Request.setAttribute("noneStarted", noneStarted);
            p_Request.setAttribute("isNotMonitoring", isNotMonitoringStr);
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(p_Request, m_Errors);
            return (p_Mapping.findForward("Global Error"));
        }
        // Forward to the jsp.
        return (p_Mapping.findForward("DaemonProxyCluster"));
    }
}
