/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.enterprise.tools.admingui.handlers;

import java.util.EventObject;
import java.lang.Thread;
import java.util.Properties;

import javax.management.MBeanException;
import javax.management.ObjectName;
import javax.management.AttributeList;
import javax.management.Attribute;
import javax.servlet.http.HttpServletRequest;

import com.iplanet.jato.RequestContext;
import com.iplanet.jato.RequestManager;
import com.iplanet.jato.view.View;
import com.iplanet.jato.view.ViewBase;
import com.iplanet.jato.view.ViewBean;
import com.iplanet.jato.util.NonSyncStringBuffer;
import com.iplanet.jato.model.DefaultModel;
import com.sun.web.ui.model.CCActionTableModelInterface;

import com.sun.enterprise.tools.guiframework.exception.FrameworkException;
import com.sun.enterprise.tools.guiframework.view.DescriptorContainerView;
import com.sun.enterprise.tools.guiframework.view.HandlerContext;
import com.sun.enterprise.tools.guiframework.view.descriptors.ViewDescriptor;
import com.sun.enterprise.tools.admingui.util.MBeanUtil;
import com.sun.enterprise.tools.admingui.util.Util;
import com.sun.enterprise.tools.admingui.AdminGUIConstants;

import com.sun.enterprise.admin.servermgmt.RuntimeStatus;
import com.sun.enterprise.admin.common.Status;


public class ServerInstGeneralHandlers {

    /**
     *
     */
    public String endPortsDisplay(RequestContext ctx, HandlerContext handlerCtx) {
        String ports = "";
        String objectName = (String)handlerCtx.getViewDescriptor().getParameter("objectName");
        // "ias:type=http-service,config=server-config,category=config"
        // "ias:type=iiop-service,config=server-config,category=config"
        String methodName = (String)handlerCtx.getViewDescriptor().getParameter("methodName");
        // "getHttpListener" or "getIiopListener"
        try {
            ObjectName[] listeners = (ObjectName[]) MBeanUtil.invoke(
                new ObjectName(objectName), methodName, null, null);

            for (int i=0; i<listeners.length; i++) {
                Object port = MBeanUtil.getAttribute(listeners[i], "port");
                if (i != 0)
                    ports += ",  ";
                if (port != null){
                    String pn = port.toString();
                    if (pn.startsWith("$")){
                        String serverName = (String)handlerCtx.getViewDescriptor().getParameter("serverName");
                        port = resolveToken( (pn.substring(2, pn.length()-1) ), serverName);
                    }
                    ports += port.toString();
                }
            }
            
        } catch (Exception ex) {
	    if (Util.isLoggableINFO()) {
		Util.logINFO("Exception thrown in getting HTTP ports.", ex);
	    }
        }

        return ports;
    }


    /**
     *
     */
    public String endConfigDirDisplay(RequestContext ctx, HandlerContext handlerCtx) {
        String objectName = (String)handlerCtx.getViewDescriptor().getParameter("objectName");
        String methodName = (String)handlerCtx.getViewDescriptor().getParameter("methodName");
        String dir = "";
        try {
            Object configDir = MBeanUtil.invoke(
                new ObjectName(objectName), methodName, null, null);
            dir += configDir.toString();
        } catch (Exception ex) {
	    if (Util.isLoggableINFO()) {
		Util.logINFO("Exception thrown in getting config directory.", ex);
	    }
        }
        return dir;
    }


    /**
     *
     */
    public String endDebugDisplay(RequestContext ctx, HandlerContext handlerCtx) {
        String objectName = (String)handlerCtx.getViewDescriptor().getParameter("objectName");
        String methodName = (String)handlerCtx.getViewDescriptor().getParameter("methodName");
        String msg = Util.getMessage("serverinst.notEnabled");
        try {
            Object debugPort = MBeanUtil.getAttribute(
                new ObjectName(objectName), methodName);

            if (debugPort != null) {
                String port = debugPort.toString();
                if (port.equals("0") == false) {
                    msg = Util.getMessage("serverinst.debugEnabled") + 
                        debugPort.toString();
                }
            }
        } catch (Exception ex) {
	    if (Util.isLoggableINFO()) {
		Util.logINFO("Exception thrown in getting debug port.", ex);
	    }
        }
        return msg;
    }


    /**
     *
     */
    public String endHostNameDisplay(RequestContext ctx, HandlerContext handlerCtx) {
	View bean = handlerCtx.getView();
        DescriptorContainerView view = (DescriptorContainerView)bean.getParent();
        return ctx.getRequest().getServerName();
    }


    /**
     *	The versioning information can be retrieved using the following mbeans:
     *	
     *	j2eeType=J2EEDomain,name=com.sun.appserv,category=runtime
     *	j2eeType=J2EEServer,name=server,category=runtime
     *	
     *	in the com.sun.appserv domain. The attributes for retrieving the version
     *	using the J2EEDomain mbean is applicationServerFullVersion and
     *	applicationServerVersion. The attribute for retrieving the version using
     *	serverVersion is serverVersion. There had been a request to have the
     *	versioning accessible via the domain and server.
     */
    public static String endInstallVersionDisplay(RequestContext ctx, HandlerContext handlerCtx) {
        String objectName = (String)handlerCtx.getViewDescriptor().getParameter("objectName");
        String methodName = (String)handlerCtx.getViewDescriptor().getParameter("methodName");
        String version = "";
        try {
            Object domainVersion = MBeanUtil.getAttribute(
                new ObjectName(objectName), methodName);
            version += domainVersion.toString();
        } catch (Exception ex) {
	    if (Util.isLoggableINFO()) {
		Util.logINFO("Exception thrown in getting domain version.", ex);
	    }
        }
        return version;
    }
    
    public void isServerRunning(RequestContext ctx, HandlerContext handlerCtx) {
        boolean isRunning = false;
	Object sts = (Object) handlerCtx.getInputValue("statusObject");
        if (sts instanceof RuntimeStatus) {
            Status s = ((RuntimeStatus)sts).getStatus();
            int code = s.getStatusCode();
            switch (code) {
                case Status.kInstanceRunningCode:
                case Status.kInstanceStartingCode:
                    isRunning = true;
                    break;
                case Status.kInstanceNotRunningCode:
                case Status.kInstanceStoppingCode:
                    isRunning = false;
                    break;
                case Status.kEntityEnabledCode:
                case Status.kEntityDisabledCode:
                    // these code should never happen
                    return; // without setting an output value
            }
        }
        handlerCtx.setOutputValue("value", (isRunning)?("true"):("false"));
    }
    
    public void loadInstanceAndNodeAgent(RequestContext ctx, HandlerContext handlerCtx) {
        try {
            CCActionTableModelInterface model =
            (CCActionTableModelInterface)handlerCtx.getInputValue("propertiesModel");  
            ObjectName[] objs = (ObjectName[] )handlerCtx.getInputValue("instanceList");
            model.beforeFirst();
            if (objs == null || objs.length < 1 )
                return;
            for(int i=0; i< objs.length; i++){
                String name = (String) MBeanUtil.getAttribute(objs[i], "name");
                String nodeAgent = (String) MBeanUtil.getAttribute(objs[i], "node-agent-ref");
                model.appendRow();
                model.setValue(PropertiesHandlers.PROPERTY_NAME, name);
                model.setValue(PropertiesHandlers.PROPERTY_VALUE ,nodeAgent);
                model.setRowSelected(false);
            }
            
        } catch (Exception ex) {
            throw new FrameworkException("loadProperties: Loading error. ", ex);
        }
    }
    
     private String resolveToken(String pn, String serverName)
    {
        if (Util.isEmpty(serverName)){
	    throw new IllegalArgumentException("The parameter map did not contain serverName");
	}
        String objectName = "com.sun.appserv:type=server,category=config,name=" + serverName;
        String methodName = "listSystemProperties"; 
        Object[] params = new Object[]{ new Boolean("true")};
        String[] types = new String[]{"boolean"};
        try {
            Properties sysProp = (Properties) MBeanUtil.invoke(new ObjectName(objectName), methodName, params, types);
            String value = sysProp.getProperty(pn);
            return value;
        }catch (Exception ex){
            throw new FrameworkException("EndPortDisplay:  ", ex);
        }
    }
    
    
}
