package net.hyperic.hq.product.mx4j;

import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.management.ObjectName;

import net.hyperic.hq.product.AutoServerDetector;
import net.hyperic.hq.product.PluginException;
import net.hyperic.hq.product.ServerDetector;
import net.hyperic.hq.product.ServerResource;
import net.hyperic.hq.product.ServiceResource;

import net.hyperic.util.config.ConfigResponse;

public class MX4JDetector
    extends ServerDetector
    implements AutoServerDetector
{
    static final String MAIN_CLASS = "net.hyperic.hq.mx4j.ExampleServer";
    static final String PTQL_QUERY = 
        "State.Name.eq=java,Args.*.eq=" + MAIN_CLASS;

    static final String PROP_SERVICE_NAME = "service.name";

    private List getServerProcessList()
    {
        List paths = new ArrayList();
        long[] pids = getPids(PTQL_QUERY);
    
        for (int i=0; i<pids.length; i++) {
            String[] args = getProcArgs(pids[i]);
            
            for (int j=0; j<args.length; j++) {
                String arg = args[j];

                if (arg.startsWith("-Dserver.home=")) {
                    paths.add(arg.substring("-Dserver.home=".length()));
                }
            }
        }

        return paths;
    }

    public List getServerResources(ConfigResponse platformConfig)
        throws PluginException {

        List servers = new ArrayList();
        List paths = getServerProcessList();
        
        for (int i=0; i<paths.size(); i++) {
            String dir = (String)paths.get(i);

            // Create the server resource
            ServerResource server = createServerResource(dir);

            // Use all defaults
            setProductConfig(server, new ConfigResponse());

            server.setMeasurementConfig();
            servers.add(server);
        }

        return servers;
    }

    protected List discoverServices(ConfigResponse serverConfig)
        throws PluginException {

        String jmxUrl = serverConfig.getValue(MX4JUtil.PROP_JMXURL);
        Set mbeans = MX4JUtil.queryNames(jmxUrl,
                                         "hyperic:type=EchoServer,*");

        List services = new ArrayList();

        for (Iterator i = mbeans.iterator(); i.hasNext();) {
            String name = ((ObjectName)i.next()).getKeyProperty("name");

            ServiceResource service = new ServiceResource();
            service.setName(name);
            
            ConfigResponse config = new ConfigResponse();
            config.setValue(PROP_SERVICE_NAME, name);

            service.setProductConfig(config);
            service.setMeasurementConfig();
            service.setControlConfig();

            services.add(service);
        }

        return services;
    }
}
