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

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

import javax.management.ObjectName;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.webapp.jonasadmin.JonasBaseAction;
import org.ow2.jonas.webapp.jonasadmin.WhereAreYou;
import org.ow2.jonas.webapp.jonasadmin.jonasmqconnect.util.ItemDestination;
import org.ow2.jonas.webapp.jonasadmin.jonasmqconnect.util.MqObjectNames;
import org.ow2.jonas.webapp.jonasadmin.jonasmqconnect.util.PropertiesComparator;
import org.ow2.jonas.webapp.jonasadmin.jonasmqconnect.util.PropertiesUtil;
import org.ow2.jonas.webapp.jonasadmin.jonasmqconnect.util.Property;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class DestinationEditAction extends JonasBaseAction {

    public ActionForward executeAction(ActionMapping mapping, ActionForm form
            , HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        DestinationEditForm fBean = (DestinationEditForm)form;
        String jndiName = fBean.getJndiName();
        String operation = fBean.getOperation();
        ArrayList properties = new ArrayList();
        ArrayList statProperties = new ArrayList();
        ObjectName mbName;

        WhereAreYou oWhere = (WhereAreYou) request.getSession().getAttribute(WhereAreYou.
                SESSION_NAME);
        String serverName = oWhere.getCurrentJonasServerName();
        String domainName = oWhere.getCurrentDomainName();

        /*
         * Get the connector name
         */
        String connector = request.getParameter("connector");
        if (connector == null) {
            connector = (String) m_Session.getAttribute("mqconnector");
        } else {
            m_Session.setAttribute("mqconnector", connector);
        }

        try {

            /*
             * FWA BEGIN : get the exact ObjectName of the destination
             */
            /* */
            mbName =  MqObjectNames.getDestinationON(domainName, jndiName, connector);

            //domain*jmq1*jonasmqconnect*jonasmqconnector*<myconnector>*destination*<mydestination>
            // Force the node selection in tree
            String nodeName = "domain" + WhereAreYou.NODE_SEPARATOR
                                + serverName + WhereAreYou.NODE_SEPARATOR
                                + "jonasmqconnect" + WhereAreYou.NODE_SEPARATOR
                                + "jonasmqconnector" + WhereAreYou.NODE_SEPARATOR
                                + connector + WhereAreYou.NODE_SEPARATOR
                                + "destination"  + WhereAreYou.NODE_SEPARATOR
                                + jndiName;
            m_WhereAreYou.selectNameNode(nodeName, true);

            /*
             * FWA END
             */

            boolean isTopic = ((Boolean) JonasManagementRepr.getAttribute(
                    mbName, "IsTopic", serverName)).booleanValue();
            fBean.setIsTopic(isTopic);
            properties.add(new Property("JndiName", jndiName, "JndiName"));
            properties.add(new Property("Type", (isTopic) ? "Topic" : "Queue",
                    "Type"));

            /*
             * FWA commented out
             */
            /*
             * TODO : check why are ALL OF THESE properties out.
             * - Class: OK. it's a java class
             * - Refernce: OK. Sums all of the properties
             * - why Version ?
             * - Why Expiry ?
             */
            String[] propertiesToSkip = new String []{"Class", "Expiry", "Reference", "Version"};
            properties = PropertiesUtil.getJMSObjectProperties(mbName, ((isTopic) ? "Topic" : "Queue"),"getProperty", propertiesToSkip, serverName, domainName);

            /*
             * FWA end
             */
            if (!isTopic) {
                int currentDepth = ((Integer) JonasManagementRepr.getAttribute(
                        mbName, "CurrentDepth",serverName)).intValue();
                int maxQueueDepth = ((Integer) JonasManagementRepr.getAttribute(
                        mbName, "MaxQueueDepth",serverName)).intValue();
                int inputCount = ((Integer) JonasManagementRepr.getAttribute(
                        mbName, "InputCount",serverName)).intValue();
                int outputCount = ((Integer) JonasManagementRepr.getAttribute(
                        mbName, "OutputCount",serverName)).intValue();

                statProperties.add(new Property("CurrentDepth", "" + currentDepth,
                        m_Resources.getMessage(
                            "label.joansmqconnect.destination.currentdepth")));
                statProperties.add(new Property("MaxQueueDepth","" + maxQueueDepth,
                        m_Resources.getMessage(
                        "label.joansmqconnect.destination.maxqueuedepth")));
                statProperties.add(new Property("InputCount", "" + inputCount,
                        m_Resources.getMessage(
                        "label.joansmqconnect.destination.inputcount")));
                statProperties.add(new Property("OutputCount", "" + outputCount,
                        m_Resources.getMessage(
                        "label.joansmqconnect.destination.outputcount")));
            }
            if ("apply".equals(operation)) {
                for (int i = 0; i < properties.size(); i++) {
                    Property property = (Property) properties.get(i);
                    property.setValue(request.getParameter(property.getName()));
                }

                PropertiesUtil.setClassProperties(mbName, /* FWA - commented out: mqClass, */
                        "setProperty", properties, serverName);
                properties = PropertiesUtil.getJMSObjectProperties(mbName, ((isTopic) ? "Topic" : "Queue"), "getProperty", propertiesToSkip, serverName, domainName);
                /* FWA - commented out: properties = PropertiesUtil.getClassProperties(mbName, mqClass,
                        "getProperty", new String []{"Version"}, serverName);
                        */
            }
            if ("clearQueue".equals(operation)) {
                Object[] params = {};
                String[] signature = {};
                JonasManagementRepr.invoke(mbName, "clearQueue", params,
                        signature, serverName);
                fBean.setOperation("view");
            }

            Collections.sort(properties, new PropertiesComparator());
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(request, m_Errors);
            return (mapping.findForward("Global Error"));
        }
        fBean.setProperties(properties);
        fBean.setStatProperties(statProperties);
        return mapping.findForward("JonasMqConnectDestinationEdit");
    }
}