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

package org.ow2.jonas.webapp.jonasadmin.service.resource;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Properties;

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.base.mbean.ObjectNameItem;
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.management.javaee.J2eeObjectName;
import org.ow2.jonas.lib.util.JonasObjectName;
import org.ow2.jonas.lib.util.JoramObjectName;
import org.ow2.jonas.webapp.jonasadmin.JonasAdminJmx;
import org.ow2.jonas.webapp.jonasadmin.JonasBaseAction;
import org.ow2.jonas.webapp.jonasadmin.WhereAreYou;
import org.ow2.jonas.webapp.jonasadmin.common.BeanComparator;


/**
 * @author Michel-Ange ANTON
 */

public class EditResourceAdapterAction extends JonasBaseAction {

    public final static String JORAM_RAR_NAME = "joram_for_jonas_ra";

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

    @Override
    public ActionForward executeAction(final ActionMapping p_Mapping, final ActionForm p_Form
        , final HttpServletRequest p_Request, final HttpServletResponse p_Response)
        throws IOException, ServletException {

        // Selected resource adapter
        String raON = p_Request.getParameter("select");

        ObjectName raObjectName = null;
        ObjectName rarObjectName = null;
        String domainName = null;
        String serverName = null;
        String rarName = null;
        String fileName = null;
        String specVersion = null;
        String appName = null;

        // Form used
        ResourceAdapterForm oForm = null;
        // Build a new form
        if (raON != null) {
            String sPath = null;
            try {
                // Recreate ResourceAdapter ObjectName
                raObjectName = ObjectName.getInstance(raON);
                domainName = raObjectName.getDomain();
                serverName = raObjectName.getKeyProperty("J2EEServer");
                rarName = raObjectName.getKeyProperty("name");
                appName = raObjectName.getKeyProperty("J2EEApplication");
                // Create the ResourceAdapterModule ObjectName
                rarObjectName = J2eeObjectName.getResourceAdapterModule(domainName, serverName, appName, rarName);

                // check Objectname
                if (!JonasManagementRepr.isRegistered(rarObjectName, serverName)) {
                    refreshServicesTree(p_Request);
                    return (p_Mapping.findForward("ActionListResourceAdapters"));
                }
                // Build a new form
                oForm = new ResourceAdapterForm();
                oForm.reset(p_Mapping, p_Request);
                oForm.setName(rarName);
                specVersion = getStringAttribute(raObjectName, "specVersion");
                oForm.setSpecVersion(specVersion);

                if (raObjectName != null) {
                    // Object name used
                    oForm.setOName(raObjectName);
                    oForm.setJndiName(getStringAttribute(raObjectName, "jndiName"));
                    fileName = getStringAttribute(raObjectName, "fileName");
                    oForm.setPath(fileName);
                    if (fileName.lastIndexOf(JORAM_RAR_NAME) > 0) {
                        // this is possibly the Joram RAR
                        ObjectName joramAdapterOn = (ObjectName) JonasManagementRepr.queryNames(JoramObjectName.joramAdapter(), serverName).iterator().next();
                        if (JonasAdminJmx.hasMBeanName(joramAdapterOn, serverName)) {
                            oForm.setJoramAdapter(true);
                            Short localServerId = (Short)JonasManagementRepr.getAttribute(joramAdapterOn, "ServerId", serverName);
                            oForm.setJoramServerId(localServerId.toString());
                            oForm.setJoramServerName((String) JonasManagementRepr.getAttribute(joramAdapterOn, "ServerName", serverName));
                        }
                    }
                    oForm.setFile(JonasAdminJmx.extractFilename(oForm.getPath()));
                    // Use the ResourceAdapterModule MBean for EAR related info
                    oForm.setInEar(getBooleanAttribute(rarObjectName, "inEarCase"));
                    oForm.setEarPath((URL) JonasManagementRepr.getAttribute(rarObjectName, "earURL", serverName));
                    oForm.setEarON((String) JonasManagementRepr.getAttribute(rarObjectName, "earON", serverName));
                    oForm.setListProperties((Properties) JonasManagementRepr.getAttribute(raObjectName
                            , "properties", serverName));

                    ObjectName oJCAResource = ObjectName.getInstance(getStringAttribute(raObjectName, "jcaResource"));

                    String [] cfs = (String[]) JonasManagementRepr.getAttribute(oJCAResource, "connectionFactories", serverName);
                    ArrayList cfAl = new ArrayList();
                    String cfOn = null;
                    for (int i = 0; i < cfs.length; i++) {
                        cfOn = cfs[i];
                        ObjectName onCf = ObjectName.getInstance(cfOn);
                        cfAl.add(new ObjectNameItem(onCf));
                    }
                    Collections.sort(cfAl, new BeanComparator(new String[] {
                            "name"}));
                    oForm.setCF(cfAl);

                    String [] ass = (String[]) JonasManagementRepr.getAttribute(oJCAResource, "activationSpecs", serverName);
                    ArrayList asAl = new ArrayList();
                    String asOn = null;
                    for (int i = 0; i < ass.length; i++) {
                        asOn = ass[i];
                        ObjectName onAs = ObjectName.getInstance(asOn);
                        asAl.add(new ObjectNameItem(onAs));
                    }
                    Collections.sort(asAl, new BeanComparator(new String[] {
                            "name"}));
                    oForm.setAS(asAl);

                    String [] aos = (String[]) JonasManagementRepr.getAttribute(oJCAResource, "adminObjects", serverName);
                    ArrayList aoAl = new ArrayList();
                    String aoOn = null;
                    for (int i = 0; i < aos.length; i++) {
                        aoOn = aos[i];
                        ObjectName onAo = ObjectName.getInstance(aoOn);
                        aoAl.add(new ObjectNameItem(onAo));
                    }
                    Collections.sort(aoAl, new BeanComparator(new String[] {
                            "name"}));
                    oForm.setAO(aoAl);

                    if (specVersion == null || specVersion.equals("1.0")) {
                        populate(oForm, cfs[0], domainName, serverName);
                    }
                }

                m_Session.setAttribute("resourceAdapterForm", oForm);
            } catch (Throwable t) {
                addGlobalError(t);
                saveErrors(p_Request, m_Errors);
                return (p_Mapping.findForward("Global Error"));
            }
        } else {
            // Used last form in session
            oForm = (ResourceAdapterForm) m_Session.getAttribute("resourceAdapterForm");
            specVersion = oForm.getSpecVersion();
        }

        // Force the node selected in tree
        m_WhereAreYou.selectNameNode(getTreeBranchName(DEPTH_SERVER) + WhereAreYou.NODE_SEPARATOR
            + "services" + WhereAreYou.NODE_SEPARATOR + "resourceAdapter"
            + WhereAreYou.NODE_SEPARATOR + oForm.getFile(), true);

        // Forward to the jsp.
        if (specVersion != null && specVersion.equals("1.5")) {
            return (p_Mapping.findForward("Resource Adapter1.5"));
        }
        return (p_Mapping.findForward("Resource Adapter1.0"));
    }

//  --------------------------------------------------------- Protected Methods

    protected void populate(final ResourceAdapterForm p_Form, final String cf, final String domainName, final String serverName)
        throws Exception {

        // ObjectName used for CF
        ObjectName oObjectName = ObjectName.getInstance(cf);
        p_Form.setConnectionFactory (cf);

        p_Form.setJdbcConnCheckLevel(toStringIntegerAttribute(oObjectName, "jdbcConnCheckLevel"));
        p_Form.setConnMaxAge(toStringIntegerAttribute(oObjectName, "connMaxAge"));
        p_Form.setMaxOpentime(toStringIntegerAttribute(oObjectName, "maxOpentime"));
        p_Form.setJdbcTestStatement(getStringAttribute(oObjectName, "jdbcTestStatement"));
        p_Form.setMaxSize(toStringIntegerAttribute(oObjectName, "maxSize"));
        p_Form.setMinSize(toStringIntegerAttribute(oObjectName, "minSize"));
        p_Form.setInitSize(toStringIntegerAttribute(oObjectName, "initSize"));
        p_Form.setMaxWaitTime(toStringIntegerAttribute(oObjectName, "maxWaitTime"));
        p_Form.setMaxWaiters(toStringIntegerAttribute(oObjectName, "maxWaiters"));
        p_Form.setSamplingPeriod(toStringIntegerAttribute(oObjectName, "samplingPeriod"));
        p_Form.setPstmtMax(toStringIntegerAttribute(oObjectName, "pstmtMax"));
        p_Form.setJdbcConnSetUp(getBooleanAttribute(oObjectName, "jdbcConnSetUp"));

        // Build list of Ejb which used this jndiName
        ArrayList al = new ArrayList();
        String[] asParam = new String[1];
        String[] asSignature = new String[1];
        asSignature[0] = "java.lang.String";
        asParam[0] = p_Form.getJndiName();
        if (JonasManagementRepr.isRegistered(JonasObjectName.ejbService(domainName), serverName)) {
            java.util.Iterator it = ((java.util.Set) JonasManagementRepr.invoke(JonasObjectName.
                ejbService(domainName), "getDataSourceDependence", 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
        p_Form.setListUsedByEjb(al);
    }
}
