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

package org.ow2.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.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.management.extensions.container.ejb.EjbItem;
import org.ow2.jonas.lib.management.extensions.container.ejb.EjbItemByNameComparator;
import org.ow2.jonas.lib.util.JonasObjectName;
import org.ow2.jonas.lib.util.JoramObjectName;
import org.ow2.jonas.webapp.jonasadmin.Jlists;
import org.ow2.jonas.webapp.jonasadmin.WhereAreYou;


/**
 * @author Adriana Danes
 */

public class EditJoramQueueAction extends EditJoramBaseAction {

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

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

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

        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, serverId, 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, oForm.getOName(), serverName));
                }
                if (!oForm.getFreelyWriteable()) {
                    // update writers list
                    List writerList = getListAttribute(oForm.getOName(), "WriterList");
                    oForm.setWriterList(getBaseItemList(writerList, oForm.getOName(), 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(domainName);
                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"));
    }
}
