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

import java.util.LinkedHashMap;
import java.util.Properties;

import javax.management.ObjectName;

import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.jmx.BrokerViewMBean;
import org.apache.activemq.broker.jmx.QueueViewMBean;

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

public class SingleQueueMonitoringForActiveMq implements JMXMonitoring {

	private static SingleQueueMonitoringForActiveMq monitoring;

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

	@Override
	public void init(Properties properties) throws Exception {

	}

	@Override
	public Object getState(String instName) throws Exception {
		LinkedHashMap<String, String[]> result = new LinkedHashMap<String, String[]>();
		BrokerService brokerService = new BrokerService();
		brokerService.getManagementContext().setCreateConnector(false);
		ObjectName brokerViewMBean = null;
		try {
			brokerViewMBean = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost");
			BrokerViewMBean borkerProxy = (BrokerViewMBean) brokerService.getManagementContext()
					.newProxyInstance(brokerViewMBean, BrokerViewMBean.class, true);
			ObjectName[] queues = borkerProxy.getQueues();
			for (ObjectName queue : queues) {
				QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(queue,
						QueueViewMBean.class, true);
				String queueName = proxy.getName();
				long l = proxy.getQueueSize();
				result.put(queueName, getCount(queueName, l));
			}
		} catch (java.lang.reflect.UndeclaredThrowableException i) {
			;
		} catch (Exception e) {
			e.printStackTrace();
		}
		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 {
		SingleQueueMonitoringForActiveMq monitoring = new SingleQueueMonitoringForActiveMq();
		Properties properties = new Properties();

		monitoring.init(properties);
		// System.out.println(monitoring.getState(""));
	}

}