/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 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.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.ow2.jonas.lib.management.domain.DomainMonitor;
import org.ow2.jonas.lib.management.domain.J2EEDomain;
import org.ow2.jonas.lib.management.domain.proxy.clusterd.ClusterDaemonProxy;
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.management.javaee.J2eeObjectName;
import org.ow2.jonas.webapp.jonasadmin.JonasBaseAction;
import org.ow2.jonas.webapp.jonasadmin.clusterd.DaemonProxyClusterConfigureServerAction;
import org.ow2.jonas.webapp.jonasadmin.common.BeanComparator;

/**
 * This action is called when adding a server to the domain (Add server button).
 * @author Adriana Danes
 */
public class CreateJonasServerAction extends JonasBaseAction {

    // --------------------------------------------------------- Public Methods
    @Override
    @SuppressWarnings("unchecked")
    public ActionForward executeAction(final ActionMapping p_Mapping, final ActionForm p_Form,
            final HttpServletRequest p_Request, final HttpServletResponse p_Response) throws IOException, ServletException {
        // Form used
        NewServerForm oForm = new NewServerForm();
        m_Session.setAttribute("newServerForm", oForm);
        String clusterName = (String) m_Session.getAttribute("currentCluster");
        String clusterDaemonName = p_Request.getParameter("CdName");
        if (clusterDaemonName == null) {
            clusterDaemonName = (String) p_Request.getAttribute("CdName");
        }
        String domainName = m_WhereAreYou.getCurrentDomainName();
        // first set the attribute to know if we alreaday have the ClusterDameon
        // name or not
        p_Request.setAttribute("CdName", clusterDaemonName);
        try {
            if (clusterDaemonName != null) {
                m_WhereAreYou.setCurrentClusterDaemonName(clusterDaemonName);
                // getting requested cluster daemon Administred Jonas servers...
                DomainMonitor dm = J2EEDomain.getInstance().getDomainMonitor();
                // Get servers running in this domain
                ArrayList al = new ArrayList();
                // are all the servers already started ?
                // getting the cluster daemon proxy from domain monitor
                ClusterDaemonProxy cdProx = dm.findClusterDaemonProxy(clusterDaemonName);
                ObjectName on = null;
                ServerItem srv = null;
                if (cdProx != null) {
                    // Retrieve servers that can be affected to a cluster daemon
                    for (Iterator it = dm.getServerList().iterator(); it.hasNext();) {
                        ServerProxy proxy = (ServerProxy) it.next();
                        on = ObjectName.getInstance(proxy.getJ2eeObjectName());
                        String cdName = proxy.getClusterDaemonName();
                        // get good candidates for being affected to a clusterd
                        if (cdName == null) {
                            srv = checkServerConfig(proxy, on);
                            al.add(srv);
                        }
                    }
                    Collections.sort(al, new BeanComparator(new String[] {"name"}));
                    // this list will be used in the forward destination.
                    p_Request.setAttribute("freeServersList", al);
                    p_Request.setAttribute("clusterdName", cdProx.getName());
                    // the session attribute will be retrieved when configuring
                    // server for clusterd affectation
                    m_Session.setAttribute("freeServersList", al);
                }
                return (p_Mapping.findForward("AddServerToClusterDaemon"));
            }
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(p_Request, m_Errors);
            return (p_Mapping.findForward("Global Error"));
        }
        // Current JOnAS server
        String jonasServerName = m_WhereAreYou.getCurrentJonasServerName();
        // Forward to the jsp.
        if (domainName.equals(clusterName)) {
            return (p_Mapping.findForward("AddServerToDomain"));
        } else {
            oForm.setCluster(true);
            ObjectName domainOn = J2eeObjectName.J2EEDomain(domainName);
            Object[] asParam = {clusterName};
            String[] asSignature = {"java.lang.String"};
            String[] serverNames = (String[]) JonasManagementRepr.invoke(domainOn, "getServersNotInCluster", asParam,
                    asSignature, jonasServerName);
            oForm.setServerNames(serverNames);
            return (p_Mapping.findForward("AddServerToCluster"));
        }
    }

    /**
     * Checks if the server is configured for clusterd affectaion if true, adds
     * it to the configured server list.
     * @param srv The server proxy
     * @param on The server on. Used to create a serverItem instance.
     * @return ServerItem correctly configured.
     * @throws Exception if a null pointer exception occurs when processing.
     */
    private ServerItem checkServerConfig(final ServerProxy srv, final ObjectName on) throws Exception {

        if (m_WhereAreYou.isConfiguredForClusterd(srv.getName())) {
            // this server is already configured for clusterd affectation.
            return m_WhereAreYou.getSrvConfiguredForClusterd(srv.getName());

        }
        // TODO test following methods. given keys should be wrong.
        ServerItem srvItem = new ServerItem(on, srv.getState(), null);
        srvItem.setJavaHome(System.getProperty("java.home"));
        srvItem.setJonasRoot(System.getProperty("jonas.root"));
        srvItem.setJonasBase(System.getProperty("jonas.base"));
        srvItem.setIsConfiguredForClusterd(false);
        srvItem.setAutoBoot(DaemonProxyClusterConfigureServerAction.DEF_AUTO_BOOT);
        srvItem.setXprem(DaemonProxyClusterConfigureServerAction.DEF_XPREM);
        if (!srv.getState().equals("UNKNOWN") && !srv.getState().equals("FAILED") && !srv.getState().equals("UNREACHABLE")) {
            // the server is running
            String javaHome = srv.getJavaHome();
            String jonasRoot = srv.getJonasRoot();
            String jonasBase = srv.getJonasBase();
            if (javaHome != null && jonasRoot != null && jonasBase != null) {
                // add the server to configured server list.
                srvItem.setJavaHome(javaHome);
                srvItem.setJonasRoot(jonasRoot);
                srvItem.setJonasBase(jonasBase);
                m_WhereAreYou.addSrvConfiguredForClusterd(srvItem);
                return srvItem;
            }

        }
        return srvItem;

    }
}
