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

package org.objectweb.jonas.webapp.jonasadmin.joramplatform;

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

import javax.management.InstanceNotFoundException;
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.JonasManagementRepr;
import org.objectweb.jonas.jmx.JonasObjectName;
import org.objectweb.jonas.jmx.JoramObjectName;
import org.objectweb.jonas.webapp.jonasadmin.Jlists;
import org.objectweb.jonas.webapp.jonasadmin.JonasAdminJmx;
import org.objectweb.jonas.webapp.jonasadmin.WhereAreYou;
import org.objectweb.jonas.webapp.jonasadmin.service.ejb.EjbItem;
import org.objectweb.jonas.webapp.jonasadmin.service.ejb.EjbItemByNameComparator;

/**
 * @author Adriana Danes
 */

public class EditJoramQueueAction extends EditJoramBaseAction {

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

    public ActionForward executeAction(ActionMapping pMapping, ActionForm pForm
        , HttpServletRequest pRequest, HttpServletResponse pResponse)
        throws IOException, ServletException {

        // Current JOnAS server
        String serverName =  m_WhereAreYou.getCurrentJonasServerName();

        String name = pRequest.getParameter("name");
        // currently managed server id
        String serverId = pRequest.getParameter("id");
        if (serverId != null) {
            m_Session.setAttribute("currentId", serverId);
        } else {
            serverId = (String) m_Session.getAttribute("currentId");
        }
        // local server id set by JonasTreeBuilder
        String localId = (String) m_Session.getAttribute("localId");
        try {
            // Check that Joram RAR still deployed
            if (JonasManagementRepr.queryNames(JoramObjectName.joramAdapter(), serverName).isEmpty()) {
                throw new InstanceNotFoundException();
            }
            // Form used
            JoramQueueForm oForm = null;
            MonitoringDestForm mForm = new MonitoringDestForm();
            if (name != null) {
                // Build a new form
                oForm = new JoramQueueForm();
                oForm.reset(pMapping, pRequest);
                // Attach the form to the session object
                m_Session.setAttribute("joramQueueForm", oForm);
                // Object name used
                ObjectName oObjectName = getDestinationOn(name, serverName);
                oForm.setOName(oObjectName);
                oForm.setBooleanVals(Jlists.getBooleanValues());
                populateDestination(oObjectName, oForm, serverName);
                getStatistics(oObjectName, mForm, oForm, serverName);
                String[] messageIdsResult = (String []) JonasManagementRepr.getAttribute(oObjectName, "MessageIds", serverName);
                StringBuffer bufMessageIds = new StringBuffer();
                for (int i = 0; i < messageIdsResult.length; i++) {
                    String joramMessageId = messageIdsResult[i];
                    bufMessageIds.append(joramMessageId);
                    bufMessageIds.append("\n");
                }
                oForm.setMessageIds(new String(bufMessageIds));
                oForm.setNbMaxMsg(getIntegerAttribute(oObjectName, "NbMaxMsg"));
                oForm.setPendingMessages(getIntegerAttribute(oObjectName, "PendingMessages"));
                oForm.setPendingRequests(getIntegerAttribute(oObjectName, "PendingRequests"));
                oForm.setThreshold(getIntegerAttribute(oObjectName, "Threshold"));
                m_Session.setAttribute("joramStatForm", mForm);
            } else {
                // Used last form in session
                oForm = (JoramQueueForm) m_Session.getAttribute("joramQueueForm");
                if (!oForm.getFreelyReadable()) {
                    // update readers list
                    List readerList = getListAttribute(oForm.getOName(), "ReaderList");
                    oForm.setReaderList(getBaseItemList(readerList, serverName));
                }
                if (!oForm.getFreelyWriteable()) {
                    // update writers list
                    List writerList = getListAttribute(oForm.getOName(), "WriterList");
                    oForm.setWriterList(getBaseItemList(writerList, serverName));
                }
                name = oForm.getName();
                if (localId == null) {
                	// TODO see with Joram team
                	/*
                    ObjectName joramPlatformON = JoramObjectName.joramPlatform();
                    localId = getStringAttribute(joramPlatformON, "LocalServerId");
                    m_Session.setAttribute("localId", localId);
                    */
                }
            }

            // Populuate dependency list
            if (name != null) {
                ArrayList al = new ArrayList();
                String[] asParam = new String[1];
                String[] asSignature = new String[1];
                asSignature[0] = "java.lang.String";
                asParam[0] = oForm.getName();
                ObjectName ejbServiceObjectName = JonasObjectName.ejbService();
                if (JonasManagementRepr.isRegistered(ejbServiceObjectName, serverName)) {
                    java.util.Iterator it = ((java.util.Set) JonasManagementRepr.invoke(
                            ejbServiceObjectName, "getJmsDestinationDependence", asParam
                            , asSignature, serverName)).iterator();
                    while (it.hasNext()) {
                        al.add(new EjbItem((ObjectName) it.next(), serverName));
                    }
                    // Sort by name
                    Collections.sort(al, new EjbItemByNameComparator());
                    // Set list in form
                    oForm.setListUsedByEjb(al);
                }
            }
        } catch (Throwable t) {
            return (treatError(t, pMapping, pRequest));
        }

        boolean isLocalServer;
        if (serverId.equals(localId)) {
            isLocalServer = true;
        } else {
            isLocalServer = false;
        }
        m_Session.setAttribute("isLocalServer", new Boolean(isLocalServer));

        // Force the node selected in tree and forward to the jsp.
        String nodeName = null;
        boolean collocatedServer = ((Boolean) m_Session.getAttribute("collocatedServer")).booleanValue();
        if (isLocalServer) {
            if (collocatedServer) {
                nodeName = getTreeBranchName(DEPTH_DOMAIN) + WhereAreYou.NODE_SEPARATOR
                + "joramplatform" + WhereAreYou.NODE_SEPARATOR
                + "joramlocalserver" + WhereAreYou.NODE_SEPARATOR
                + "joramqueue" + name;
            } else {
                nodeName = getTreeBranchName(DEPTH_DOMAIN) + WhereAreYou.NODE_SEPARATOR
                + "joramplatform" + WhereAreYou.NODE_SEPARATOR
                + "joramcurrentserver" + WhereAreYou.NODE_SEPARATOR
                + "joramqueue" + name;

            }
        } else {
            nodeName = getTreeBranchName(DEPTH_DOMAIN) + WhereAreYou.NODE_SEPARATOR
                    + "joramplatform" + WhereAreYou.NODE_SEPARATOR
                    + "joramremoteserver" + serverId + WhereAreYou.NODE_SEPARATOR
                    + "joramqueue" + name;
        }
        m_WhereAreYou.selectNameNode(nodeName, true);
        return (pMapping.findForward("JoramQueue"));
    }
}
