/**
 * 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 EditJoramTopicAction 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
            JoramTopicForm oForm = null;
            MonitoringDestForm mForm = new MonitoringDestForm();
            if (name != null) {
                // Build a new form
                oForm = new JoramTopicForm();
                oForm.reset(pMapping, pRequest);
                // Attach the form to the session object
                m_Session.setAttribute("joramTopicForm", 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);
                oForm.setSubscriptions(getIntegerAttribute(oObjectName, "Subscriptions"));
                String[] subscriberIds = (String []) JonasManagementRepr.getAttribute(oObjectName, "SubscriberIds", serverName);
                StringBuffer buf = new StringBuffer();
                for (int i = 0; i < subscriberIds.length; i++) {
                    String subscriberId = subscriberIds[i];
                    String subsriberName = getUserName(subscriberId, serverName);
                    if (subsriberName == null) {
                        //throw new Exception("Problem with " + name + " topic subscribers: could not found any user having id=" + subscriberId);
                        subsriberName = subscriberId;
                    }
                    buf.append(subsriberName);
                    buf.append("\n");
                }
                oForm.setSubscribers(new String(buf));
                m_Session.setAttribute("joramStatForm", mForm);
            } else {
                // Used last form in session
                oForm = (JoramTopicForm) m_Session.getAttribute("joramTopicForm");
                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
                }
            }

            // 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] = name;
                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
                + "joramtopic" + name;
            } else {
                nodeName = getTreeBranchName(DEPTH_DOMAIN) + WhereAreYou.NODE_SEPARATOR
                + "joramplatform" + WhereAreYou.NODE_SEPARATOR
                + "joramcurrentserver" + WhereAreYou.NODE_SEPARATOR
                + "joramtopic" + name;

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

}
