/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 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
 *
 * Initial developer(s): ____________________________________.
 * Contributor(s): ______________________________________.
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.jmx.vjadmin.servlet;

// servlet imports
import javax.servlet.*;
import javax.servlet.http.*;

// standard imports
import java.util.Date;
import java.util.Properties;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Iterator;
import java.util.StringTokenizer;

// velocity imports
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.servlet.VelocityServlet;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;

// JOnAS JMX imports
import org.objectweb.jonas.jmx.*;
// JMX
import javax.management.ObjectName;

// Jadmin imports
import org.objectweb.jonas.jmx.vjadmin.*;

// monolog imports
import org.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;

// JOnAS log imports
import org.objectweb.jonas.common.Log;

public class ContainerServiceServlet extends VelocityServlet {
    static private Logger logger = null;

    public void init(ServletConfig config ) throws ServletException {
	super.init(config);
	logger = Log.getLogger(ServletLog.JONAS_VELO_SERVLET_PREFIX);
    }
    /** 
     * Creates a VelocityContext. 
     */
    protected Context createContext( HttpServletRequest request, HttpServletResponse response) { 
	HttpSession session = request.getSession();
	// Try to get the initial VelocityContext
	VelocityContext initialContext = (VelocityContext)session.getAttribute("initialContext");
	if (initialContext == null) {
	    // initial context lost, recreate it
	    initialContext = InitVeloContext.doIt(session);
	    logger.log(BasicLevel.DEBUG, "Initial VelocityContext lost. Create, initialize and attach to the session a new initial VelocityContext");
	}
	VelocityContext context = new VelocityContext(initialContext);
	logger.log(BasicLevel.DEBUG, "Create a new VelocityContext containing the initial one");
	return context;
    }

    /**
     *
     *
     *  @param ctx a Velocity Context object to be filled with
     *             data.  Will be used for rendering this 
     *             template
     *  @return Template to be used for request
     */   

    public Template handleRequest( HttpServletRequest request, 
				   HttpServletResponse response, 
				   Context context ) { 

	// Exception treatement
	String alertException = null;

 	// Get Date
	String date = java.text.DateFormat.getInstance().format(new Date());
	context.put("date", date);

	// Get request parameters
	try {
	    for (Enumeration e = request.getParameterNames() ; e.hasMoreElements() ;) {
		String paramName = (String)e.nextElement();
		if (paramName.equals("remove")) {
		    Object[] param = { request.getParameter("remove") };
		    String[] signature = { "java.lang.String" };
		    JonasManagementRepr.invoke(JonasObjectName.ejbService(), 
					       "removeContainer", param, signature);
		} else if (paramName.equals("create")) {
		    Object[] param = { request.getParameter("create") };
		    String[] signature = { "java.lang.String" };
		    JonasManagementRepr.invoke(JonasObjectName.ejbService(), 
					       "createContainer", param, signature);
		} else if (paramName.equals("run")) {
		    Object[] param = new Object[0];
		    String[] signature = new String[0];
		    JonasManagementRepr.invoke(JonasObjectName.ejbService(), 
					       request.getParameter("run"), param, signature);
		}
	    }
	} catch (ManagementException e) {
	    alertException = Script.alert(e.getMessage());
	    context.put("alertException", alertException);
	}

	// Get the name of the current JOnAS server
	boolean existsServer = JonasManagementRepr.isRegistered(JonasObjectName.ejbServer());
	context.put("existsServer", new Boolean(existsServer));
	if (existsServer) {
	    String serverName = (String)JonasManagementRepr.getAttribute(JonasObjectName.ejbServer(), "JonasName");
	    context.put("serverName", serverName);
	    
	    // Get information about the Containers currently in the server
	    // For doing this, the corresponding MBean has to be registered
	    ObjectName ejbServiceName = JonasObjectName.ejbService();
	    boolean isRegisteredContainerService = JonasManagementRepr.isRegistered(ejbServiceName);
	    context.put("isRegisteredContainerService", new Boolean(isRegisteredContainerService));
	    if (isRegisteredContainerService) {
		String contService_error = "";
		Vector containers = new Vector();
		try {
		    Integer nbContainers = (Integer)JonasManagementRepr.getAttribute(ejbServiceName, "CurrentNumberOfContainer");
		    context.put("nbContainers", nbContainers);

		    java.util.Set allContainers = JonasManagementRepr.queryNames(JonasObjectName.allContainers());
		    for (Iterator i = allContainers.iterator(); i.hasNext() ;) {			
			ObjectName current = (ObjectName)i.next();
			String fileName = (String)JonasManagementRepr.getAttribute(current, "FileName");
			String containerName = (String)JonasManagementRepr.getAttribute(current, "ContainerName");
			containers.add(new ContainerInfo(containerName, fileName.replace(' ', '+')));
		    }
		    context.put("containers", containers);		    		    
		} catch (ManagementException e) {
		    contService_error = e.getMessage();
		}
		context.put("contService_error", contService_error);

		String beans_error = "";
		Integer totalCurrentNumberOfBeanType = null;
		Integer totalCurrentNumberOfBMPType = null;
		Integer totalCurrentNumberOfCMPType = null;
		Integer totalCurrentNumberOfSBFType = null;
		Integer totalCurrentNumberOfSBLType = null;
		Integer totalCurrentNumberOfMDBType = null;
		try {
		    totalCurrentNumberOfBeanType = (Integer)JonasManagementRepr.getAttribute(ejbServiceName, "TotalCurrentNumberOfBeanType");
		    totalCurrentNumberOfBMPType = (Integer)JonasManagementRepr.getAttribute(ejbServiceName, "TotalCurrentNumberOfBMPType");
		    totalCurrentNumberOfCMPType = (Integer)JonasManagementRepr.getAttribute(ejbServiceName, "TotalCurrentNumberOfCMPType");
		    totalCurrentNumberOfSBFType = (Integer)JonasManagementRepr.getAttribute(ejbServiceName, "TotalCurrentNumberOfSBFType");
		    totalCurrentNumberOfSBLType = (Integer)JonasManagementRepr.getAttribute(ejbServiceName, "TotalCurrentNumberOfSBLType");
		    totalCurrentNumberOfMDBType = (Integer)JonasManagementRepr.getAttribute(ejbServiceName, "TotalCurrentNumberOfMDBType");
		    context.put("totalCurrentNumberOfBeanType", totalCurrentNumberOfBeanType);
		    context.put("totalCurrentNumberOfBMPType", totalCurrentNumberOfBMPType);
		    context.put("totalCurrentNumberOfCMPType", totalCurrentNumberOfCMPType);
		    context.put("totalCurrentNumberOfSBFType", totalCurrentNumberOfSBFType);
		    context.put("totalCurrentNumberOfSBLType", totalCurrentNumberOfSBLType);
		    context.put("totalCurrentNumberOfMDBType", totalCurrentNumberOfMDBType);
		} catch (ManagementException e) {
		    beans_error = e.getMessage();
		}
		context.put("beans_error", beans_error);
	    }
	} 

	// Return template
	Template template = null;
	try {
	    template = getTemplate("CONTAINER_SERVICE.vm"); 
	} catch (ParseErrorException pee ) {
            logger.log(BasicLevel.ERROR, "Parse error for template " + pee);
        } catch( ResourceNotFoundException rnfe) {
            logger.log(BasicLevel.ERROR, "Template not found " + rnfe);
        } catch( Exception e) {
            logger.log(BasicLevel.ERROR, "Error " + e);
        }

	return template;
    }

    /**
     * @param msg The error title.
     * @param msg The error message.
     * @return a string displaying the error msg in tr tags.
     */
    protected String alert(String msg) {
	StringBuffer sb = new StringBuffer("<script>alert(\"");
	StringTokenizer st = new StringTokenizer(msg, "\n");
	while (st.hasMoreTokens()) 
	    sb.append(st.nextToken()+"\\n");
	sb.append("\")</script>");
	return new String(sb);
    }
}
