/*
 * 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.admin.jmx;

//JMX imports
import javax.management.ObjectName;

import com.sun.enterprise.admin.meta.MBeanDescriptor;
import com.sun.enterprise.admin.meta.MBeanRegistry;

//Admin imports
/*import com.iplanet.ias.admin.common.ObjectNames;
import com.iplanet.ias.admin.common.ObjectNameHelper;
import com.iplanet.ias.admin.common.exception.MBeanConfigException;
import com.iplanet.ias.admin.util.HostAndPort;
//import com.iplanet.ias.admin.server.core.mbean.config.*;
import com.iplanet.ias.admin.common.constant.AdminConstants;
import com.iplanet.ias.admin.server.core.mbean.config.GenericConfigurator;
import com.iplanet.ias.admin.server.core.mbean.config.ServerController;
import com.iplanet.ias.admin.server.core.mbean.config.ManagedAdminServerInstance;
import com.iplanet.ias.admin.server.core.mbean.config.ManagedServerInstance;
import com.iplanet.ias.admin.server.core.mbean.config.naming.ConfigMBeanNamingInfo;

 */

//Other imports
//import com.iplanet.ias.config.serverbeans.*;
//import com.iplanet.ias.instance.ServerManager;

import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Set;
import java.util.List;

import javax.management.modelmbean.ModelMBean;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;

import javax.management.modelmbean.ModelMBeanInfo;
import javax.management.Descriptor;

//import org.apache.commons.modeler.ManagedBean;
//import org.apache.commons.modeler.Registry;
//import org.apache.commons.modeler.FieldInfo;

import com.sun.enterprise.admin.meta.MBeanRegistry;

import java.io.InputStream;
import java.net.URL;

//i18n import
//import com.iplanet.ias.util.i18n.StringManager;


/**
	A class to construct proper type of MBean from its object name. This
	class gives the instances of mbeans that would be registered as given
	object names.
*/

public class MBeanManufacturer
{
    private static MBeanRegistry registry = null;
    /*
    private ObjectName  mObjectName = null;
    private	Object      mConfigBean = null;

  //  private static final Logger _logger = Logger.getLogger(AdminConstants.kLoggerName);
	
    // i18n StringManager
	private static StringManager localStrings =
		StringManager.getManager( MBeanManufacturer.class );
	
    public MBeanManufacturer (ObjectName oName, Object configBean) 
    {
        if (oName == null || configBean == null)
        {
			String msg = localStrings.getString( "admin.server.core.jmx.storage.null_object_name_or_config_bean" );
            throw new IllegalArgumentException( msg );
        }
        mObjectName = oName;
        mConfigBean = configBean;
    }

    /**
        Returns an instance of proper MBean. This is required, when somebody
        wants to create the MBean for the first time in MBean Repository.
        The necessary parameters for MBean construction are derived from the
        configBean passed during consruction of this class.\
        @return instance of proper MBean corresponding to ObjectName. ObjectName
        is passed during the construction of this class. May not be null.
    * /
    public Object createMBeanInstance()
    {
        Object mbeanInstance = null;

        String type         = ObjectNameHelper.getType(mObjectName);
        String instanceName = ObjectNameHelper.getServerInstanceName(mObjectName);
        Level logLevel = Level.SEVERE;

        try
        {
            if (type.equals(ObjectNames.kController))
            {
                mbeanInstance = new ServerController();
            }
            else if (type.equals(ObjectNames.kGenericConfigurator))
            {
                mbeanInstance = new GenericConfigurator();
            }
            else if (type.equals(ObjectNames.kServerInstance))
            {
                if (instanceName.equals(ServerManager.ADMINSERVER_ID))
                {
                    mbeanInstance = createAdminServerInstance();
                }
                else
                {
                    mbeanInstance = createServerInstanceMBean(instanceName);
                }
            }
            else 
            {
                logLevel = Level.FINE;
                mbeanInstance = createGenericConfigMBean(mObjectName);
            }
        }
        catch(Exception e)
        {
            _logger.log(logLevel, "mbean.config.admin.create_mbean_instance_failed",  e );
        }
        
        return ( mbeanInstance );
    }
	
    private ManagedServerInstance createServerInstanceMBean(String instanceName) throws Exception
    {
        Server server = (Server)mConfigBean;
        HttpService https = server.getHttpService();
        
        HttpListener[] hlArray = https.getHttpListener();
        //check not needed since there should always be atleast 1 httplistener
        //if you don't find one, use first one.
        HttpListener ls = hlArray[0];  
        //default is the first one that is enabled.
        for(int i = 0;i<hlArray.length;i++) {
            if(hlArray[i].isEnabled()) {
                ls = hlArray[i];
                break;
            }
        }
        String port = ls.getPort();
        int intPort = Integer.parseInt (port);
        HostAndPort hp = new HostAndPort("localhost", intPort);
        return new ManagedServerInstance(instanceName, hp, false);
    }

    private ManagedAdminServerInstance createAdminServerInstance() 
        throws Exception
    {
        return new ManagedAdminServerInstance();
    }

    private Object createGenericConfigMBean(ObjectName objectName) throws MBeanConfigException
    {
        ConfigMBeanNamingInfo mbeanInfo = new ConfigMBeanNamingInfo(objectName);
        return mbeanInfo.constructConfigMBean();
    }

     */
    
    static void findPersistent(ObjectName name) {
        System.out.println("Find persistant for "+name);
        org.apache.commons.modeler.Registry rr;
        //FIXME: may be we can have more than 1 registries.
        if(registry == null) createRegistry();
        try {
        
        MBeanServer server = (MBeanServer)MBeanServerFactory.findMBeanServer(null).get(0);            
        
        //already exists.
        Set result = server.queryMBeans(name, null);
        if(result != null && result.size() !=0) return;
        
        //krav - find naming descriptor by object name    
        ModelMBean mm = MBeanDescriptor.instantiateMBean(name, null);

        //TEST PRINT
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> info from Model mbean <<<<<<<<<<<<<<<<<<<<<<<<<");
        ModelMBeanInfo inf = (ModelMBeanInfo)mm.getMBeanInfo();
        System.out.println(">>info="+ inf);
        Descriptor md = inf.getMBeanDescriptor();
        System.out.println(">>mbdescr="+ md);
        System.out.println(">>location="+ md.getFieldValue("persistLocation"));
        System.out.println(">>>>>>>description="+ inf.getDescription());

           //test code
           // com.sun.enterprise.admin.config.EjbContainerTest demo = 
            //    new com.sun.enterprise.admin.config.EjbContainerTest();
            
            //mm.addAttributeChangeNotificationListener(demo, "shutdown", null);
            
//            server.registerMBean(mm, name);

        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * Create and configure the registry of managed objects.
     */
    private static void createRegistry() {

        System.out.println("Create configuration registry ...");
        try {
            URL url = MBeanManufacturer.class.getResource
                ("/mbeans-descriptors.xml");
            InputStream stream = url.openStream();
            registry = new MBeanRegistry();
            registry.loadMBeanRegistry(stream);
            stream.close();
        } catch (Throwable t) {
            t.printStackTrace(System.out);
            System.exit(1);
        }

    }
    
}
