/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2007 Bull S.A.S
 * 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: ApplyJonasServersAction.java 18042 2009-07-24 08:52:44Z eyindanga $$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.webapp.jonasadmin.clusterd;

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

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.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.util.JonasObjectName;
import org.ow2.jonas.webapp.jonasadmin.JonasBaseAction;
import org.ow2.jonas.webapp.jonasadmin.domain.ItemsServersForm;

/**
 * Implement actions for servers management in the domain
 * @author Adriana Danes
 */
/**
 * @author eyindanga
 */
public class ApplyJonasServersAction extends JonasBaseAction {

    // --------------------------------------------------------- Public Methods
    /**
     * @param p_Mapping
     * @param p_Form
     * @param p_Request
     * @param p_Response
     * @return
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public ActionForward executeAction(final ActionMapping p_Mapping, final ActionForm p_Form,
            final HttpServletRequest p_Request, final HttpServletResponse p_Response) throws IOException, ServletException {

        // Form used
        try {
            String sDomainName = m_WhereAreYou.getCurrentDomainName();
            String serverName = m_WhereAreYou.getAdminJonasServerName();
            ItemsServersForm oForm = (ItemsServersForm) p_Form;
            String action = oForm.getAction();
            // get the selected items
            String[] selectedItems = oForm.getSelectedItems();
            // Save config in clusted.xml ? default = no
            String saveIt = "false";
            DomainMonitor dm = J2EEDomain.getInstance().getDomainMonitor();
            String curSrvName = null;
            // get the current clusterd proxy
            String cdName = m_WhereAreYou.getCurrentClusterDaemonName();
            ClusterDaemonProxy cdProxy = dm.findClusterDaemonProxy(cdName);
            if (cdProxy == null) {
                // this cluster daemon proxy is not yet registered
                registerClusterdProxy(cdName, dm);
            }
            ServerItem srvItem = null;
            if ("add".equals(action)) {
                ArrayList srvList = (ArrayList) m_Session.getAttribute("freeServersList");
                // Add selected servers to the current cluster daemon
                for (int i = 0; i < selectedItems.length; i++) {
                    // save config in clusted.xml
                    curSrvName = selectedItems[i];
                    ServerProxy srvProxy = dm.findServerProxy(curSrvName);
                    srvProxy.setClusterdaemon(cdProxy);
                    // get The server item associated to this server name
                    srvItem = findSrvItem(curSrvName, srvList);
                    // check if the server has been removed from current server
                    if (m_WhereAreYou.isSrvRemovedFromClusterd(cdName, curSrvName)) {
                        // Remove the server from removed servers list
                        m_WhereAreYou.rmvFromClusterdRemovedList(cdName, curSrvName);
                    }
                    cdProxy.addServer(srvItem.getName(), srvItem.getDescription(), srvItem.getJonasRoot(),
                            srvItem.getJonasBase(), srvItem.getJavaHome(), srvItem.getXprem(),
                            srvItem.getAutoBoot(), "", saveIt);
                }

            } else if ("remove".equals(action)) {
                // remove servers without saving
                for (int i = 0; i < selectedItems.length; i++) {
                    ServerProxy srvProxy = dm.findServerProxy(selectedItems[i]);

                    curSrvName = selectedItems[i];
                    // get The server item associated to this server name
                    ObjectName on = JonasObjectName.clusterDaemonProxy(sDomainName, cdName);
                    m_WhereAreYou.addRemovedServer(cdName, curSrvName);
                    String[] opParams = {curSrvName, saveIt};
                    String[] opSignature = {"java.lang.String", "java.lang.String"};
                    // remove the server from clusterd control
                    JonasManagementRepr.invoke(on, "removeServer", opParams, opSignature, serverName);
                    dm.findServerProxy(selectedItems[i]).setClusterdaemon(null);

                }

            } else if ("removeAndSave".equals(action)) {
                // remove servers without saving
                for (int i = 0; i < selectedItems.length; i++) {
                    ServerProxy srvProxy = dm.findServerProxy(selectedItems[i]);
                    // save the configuration
                    saveIt = "true";
                    curSrvName = selectedItems[i];
                    // get The server item associated to this server name
                    ObjectName on = JonasObjectName.clusterDaemonProxy(sDomainName, cdName);
                    m_WhereAreYou.addRemovedServer(cdName, curSrvName);
                    String[] opParams = {curSrvName, saveIt};
                    String[] opSignature = {"java.lang.String", "java.lang.String"};
                    // remove the server from clusterd control
                    JonasManagementRepr.invoke(on, "removeServer", opParams, opSignature, serverName);
                    dm.findServerProxy(selectedItems[i]).setClusterdaemon(null);

                }
            } else if ("addAndSave".equals(action)) {
                // add the server and save it
                ArrayList srvList = (ArrayList) m_Session.getAttribute("freeServersList");
                saveIt = "true";
                // Add selected servers to the current cluster daemon
                for (int i = 0; i < selectedItems.length; i++) {
                    // save config in clusted.xml
                    curSrvName = selectedItems[i];
                    ServerProxy srvProxy = dm.findServerProxy(curSrvName);
                    srvProxy.setClusterdaemon(cdProxy);
                    // get The server item associated to this server name
                    srvItem = findSrvItem(curSrvName, srvList);
                    cdProxy.addServer(srvItem.getName(), srvItem.getDescription(), srvItem.getJonasRoot(),
                            srvItem.getJonasBase(), srvItem.getJavaHome(), srvItem.getXprem(),
                            srvItem.getAutoBoot(), "", saveIt);
                }

            } else if ("removeFromView".equals(action)) {
                ArrayList al = (ArrayList) m_Session.getAttribute("freeServersList");
                for (int i = 0; i < selectedItems.length; i++) {
                    ServerProxy srvProxy = dm.findServerProxy(selectedItems[i]);
                    al = removeServerItem(al, srvProxy.getName());
                }
                p_Request.setAttribute("freeServersList", al);
                p_Request.setAttribute("clusterdName", cdProxy.getName());
                return (p_Mapping.findForward("AddServerToClusterDaemon"));
            }

            // we're not in monitoring mode
            p_Request.setAttribute("isNotMonitoring", "true");
            if (p_Request.getAttribute("node") == null) {
                p_Request.setAttribute("node", cdName);
            }
            oForm.setAction("");
            // forward to jsp that displays clusterd infos
            return p_Mapping.findForward("ActionDaemonProxyClusterInfoFromDomain");

        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(p_Request, m_Errors);
            return (p_Mapping.findForward("Global Error"));
        }
    }

    /**
     * Register a cluster daemon proxy in the domain monitor
     * @param cdName cluster daemon's name
     * @param dm the domain monitor instance
     * @throws MalformedObjectNameException ObjectName exception
     */

    private void registerClusterdProxy(final String cdName, final DomainMonitor dm) throws MalformedObjectNameException {
        String sDomainName = m_WhereAreYou.getCurrentDomainName();
        String srvName = m_WhereAreYou.getAdminJonasServerName();
        ObjectName on = JonasObjectName.clusterDaemonProxy(sDomainName, cdName);
        Collection urls = (Collection) JonasManagementRepr.getAttribute(on, "JmxUrl", srvName);
        dm.registerClusterDaemonProxy(cdName, srvName, urls);

    }

    /**
     * Find a server item associated to the given server name
     * @param itemName Find associated serverItem of this name
     * @param itemSrvList the serverItems list that has been retrieved from
     *        session
     * @return the associated serverItem
     */

    private ServerItem findSrvItem(final String itemName, final ArrayList itemSrvList) {
        int i = 0;
        boolean stop = false;
        ServerItem srv = null;
        while (!stop && i < itemSrvList.size()) {
            srv = (ServerItem) itemSrvList.get(i);
            stop = srv.getName().equals(itemName.toString());
            i++;

        }
        // we should always find the item
        return srv;
    }

    /**
     * Removes given server from current free servers list
     * @param freeServersList free servers
     * @param srvName the server to remove
     * @return
     */

    private ArrayList removeServerItem(final ArrayList freeServersList, final String srvName) {
        ArrayList ret = new ArrayList();
        for (int i = 0; i < freeServersList.size(); i++) {

            ServerItem srv = (ServerItem) freeServersList.get(i);
            if (srv.getName().equals(srvName)) {
                freeServersList.remove(i);
            } else {
                ret.add(freeServersList.get(i));
            }

        }
        return ret;
    }

}
