package com.eactive.eai.rms.client.service.weblogic;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.Properties;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;

import com.eactive.eai.rms.client.service.JMXMonitoring;

public class SingleQueueMonitoringForWebLogic implements JMXMonitoring {
//	private static MBeanServerConnection connection;
//	private static JMXConnector connector;
	private String hostname ;
	private String portString ;
	private String username ;
	private String password ;
	
	
	private static SingleQueueMonitoringForWebLogic monitoring;

	public static SingleQueueMonitoringForWebLogic getInstance(){
        if(monitoring == null) {
            synchronized(SingleQueueMonitoringForWebLogic.class) {
                if(monitoring == null) {
                	monitoring = new SingleQueueMonitoringForWebLogic();   
                }   
            }
        }
        return monitoring;
	}

	@Override
	public void init(Properties properties) throws Exception {
		hostname   = properties.getProperty("LOCAL_MBEAN_SERVER_IP");
		portString = properties.getProperty("LOCAL_MBEAN_SERVER_PORT");
		username   = properties.getProperty("LOCAL_MBEAN_SERVER_ID");
		password   = properties.getProperty("LOCAL_MBEAN_SERVER_PASSWORD");
		
	}

	@Override
	public Object getState(String instName) throws Exception {
		LinkedHashMap<String,String[]> result = new LinkedHashMap<String,String[]>();
		JMXConnector connector = null;
		MBeanServerConnection connection =null;
		
    	try {
    		String protocol ="t3";
    		Integer portInteger = Integer.valueOf(portString);
    		int port = portInteger.intValue();
    		String jndiroot = "/jndi/";
    		String mserver = "weblogic.management.mbeanservers.domainruntime";
    		JMXServiceURL serviceURL = new JMXServiceURL(protocol, hostname, port, jndiroot + mserver);
    		Hashtable h = new Hashtable();
    		h.put(Context.SECURITY_PRINCIPAL, username);
    		h.put(Context.SECURITY_CREDENTIALS, password);
    		h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
    		connector = JMXConnectorFactory.connect(serviceURL,h);
    		connection = connector.getMBeanServerConnection();
			
	    	ObjectName serviceRuntime = new ObjectName("com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean,Location="+instName);
	    	ObjectName serverRuntime = (ObjectName)connection.getAttribute(serviceRuntime, "ServerRuntime") ;
	    	ObjectName jmsRuntime = (ObjectName)connection.getAttribute(serverRuntime, "JMSRuntime") ;
	    	ObjectName[] jmsServers = (ObjectName[])connection.getAttribute(jmsRuntime, "JMSServers") ;
	    	
	    	HashMap<String,Long> queue = new HashMap<String,Long>();
	    	
	    	for(ObjectName jmsServer : jmsServers){
	    		String name = jmsServer.getKeyProperty("Name");
	    		if (name == null) continue;
	    		
	    		if(name.startsWith("JMSServer")){
	    			ObjectName[] destinations = (ObjectName[])connection.getAttribute(jmsServer, "Destinations");
	    			for(ObjectName destination : destinations){
	    				String queueName = destination.getKeyProperty("Name");
	    				if (queueName.contains("!")){
	    					queueName = queueName.substring(queueName.indexOf("!")+1);
	    				}
	    				if (queueName.contains("Topic")) continue;
	    				
	    				Long queueDepth = (Long) connection.getAttribute(destination, "MessagesCurrentCount");
	    				queue.put(queueName, queueDepth);
	//    				System.out.println("Queue : " + queueName +" Depth : " + queueDepth);
	    			}
	    		}
	    	}
	    	for(String queueName : queue.keySet()){
	    		result.put(queueName, getCount(queueName, queue.get(queueName) ));
	    	}
		}finally{
			if (connector != null){try{connector.close();}catch(Exception e){}}
		}
		return result;
	}
	private String[] getCount(String queueName, long depth) throws Exception{
		String[] info = new String[9];
		info[0] = queueName;
		info[1] = "queue";//jmsDestinationRuntimes[j].getDestinationType();
		info[2] = "0";//jmsDestinationRuntimes[j].getConsumersCurrentCount();
		info[3] = "0";//jmsDestinationRuntimes[j].getConsumersHighCount();
		info[4] = "0";//jmsDestinationRuntimes[j].getConsumersTotalCount();
		info[5] = Long.toString(depth);
		info[6] = "0";//jmsDestinationRuntimes[j].getMessagesHighCount();
		info[7] = "0";//jmsDestinationRuntimes[j].getMessagesPendingCount();
		info[8] = "0";//jmsDestinationRuntimes[j].getMessagesReceivedCount();
		return info;
	}
	public static void main(String[] args)throws Exception{
		SingleQueueMonitoringForWebLogic monitoring = new SingleQueueMonitoringForWebLogic();
		Properties properties = new Properties();
		properties.put("LOCAL_MBEAN_SERVER_IP", "172.16.131.11");
		properties.put("LOCAL_MBEAN_SERVER_PORT", "30100");
		properties.put("LOCAL_MBEAN_SERVER_ID", "epostadm");
		properties.put("LOCAL_MBEAN_SERVER_PASSWORD", "welcome1!");
		
		monitoring.init(properties);
		// System.out.println(monitoring.getState("mccSvr11"));
	}


}
