/*
 * 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;

// 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 JMSServiceServlet 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("removeDestination")) {
		    Object[] param = { request.getParameter("removeDestination") };
		    String[] signature = { "java.lang.String" };
		    JonasManagementRepr.invoke(JonasObjectName.jmsService(), 
					       "removeJmsDestination", 
					       param, 
					       signature);
		}if ((paramName.equals("createDestination")) 
		     && (request.getParameter("type").equals("topic"))) {
		    Object[] param = { request.getParameter("createDestination") };
		    String[] signature = { "java.lang.String" };
		    JonasManagementRepr.invoke(JonasObjectName.jmsService(), 
					       "createJmsTopicDestination", 
					       param, 
					       signature);
		}if ((paramName.equals("createDestination")) 
		     && (request.getParameter("type").equals("queue"))) {
		    Object[] param = { request.getParameter("createDestination") };
		    String[] signature = { "java.lang.String" };
		    JonasManagementRepr.invoke(JonasObjectName.jmsService(), 
					       "createJmsQueueDestination", 
					       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 JMS service
	boolean existsJMSService = JonasManagementRepr.isRegistered(JonasObjectName.jmsService());
	context.put("existsJMSService", new Boolean(existsJMSService));
	if (existsJMSService) {
	    java.util.Set allJms = null;// used for running over several type of JMS ressources

	    // Get default Topic Connection Factory
	    String defaultTCF = (String)JonasManagementRepr.getAttribute(JonasObjectName.jmsService(), "DefaultTopicConnectionFactoryName");
	    context.put("defaultTCF", defaultTCF);

	    // Get default Queue Connection Factory
	    String defaultQCF = (String)JonasManagementRepr.getAttribute(JonasObjectName.jmsService(), "DefaultQueueConnectionFactoryName");
	    context.put("defaultQCF", defaultQCF);

	    // Get info about Topic destinations
	    Vector topicObjects = new Vector();
	    Integer nbTopic = (Integer)JonasManagementRepr.getAttribute(JonasObjectName.jmsService(), 
						 "CurrentNumberOfJmsTopicDestination");
	    context.put("nbTopic", nbTopic);
	    allJms = (java.util.Set)JonasManagementRepr.getAttribute(JonasObjectName.jmsService(), "AllJmsTopicDestinationNames");
	    for (Iterator i = allJms.iterator(); i.hasNext() ;) {
		    String current = (String)i.next();
		    Object[] param = { current };
		    String[] signature = { "java.lang.String" };
		    boolean existDependencies = ((java.util.Set)JonasManagementRepr.invoke(JonasObjectName.ejbService(), "getJmsDestinationDependence", param, signature)).isEmpty();
		    topicObjects.add(new AdminObject(current.replace(' ', '+'), existDependencies));
	    }
	    context.put("topicObjects", topicObjects);

	    // Get info about Queue destinations
	    Vector queueObjects = new Vector();
	    Integer nbQueue = (Integer)JonasManagementRepr.getAttribute(JonasObjectName.jmsService(), 
						 "CurrentNumberOfJmsQueueDestination");
	    context.put("nbQueue", nbQueue);
	    allJms = (java.util.Set)JonasManagementRepr.getAttribute(JonasObjectName.jmsService(), "AllJmsQueueDestinationNames");
	    for (Iterator i = allJms.iterator(); i.hasNext() ;) {
		    String current = (String)i.next();
		    Object[] param = { current };
		    String[] signature = { "java.lang.String" };
		    boolean existDependencies = ((java.util.Set)JonasManagementRepr.invoke(JonasObjectName.ejbService(), "getJmsDestinationDependence", param, signature)).isEmpty();
		    queueObjects.add(new AdminObject(current.replace(' ', '+'), existDependencies));
	    }
	    context.put("queueObjects", queueObjects);
	}

	// Return template
	Template template = null;
	try {
	    template = getTemplate("JMS.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;
    }
}
