package com.sun.messaging.jmq.jmsclient.runtime.impl;

import javax.jms.JMSException;

import com.sun.messaging.jmq.jmsclient.ConnectionImpl;
import com.sun.messaging.jmq.jmsclient.runtime.BrokerInstance;
import com.sun.messaging.jmq.jmsclient.runtime.ClientRuntime;
import com.sun.messaging.jmq.jmsservice.DirectBrokerConnection;

public class ClientRuntimeImpl extends ClientRuntime {
	
	private BrokerInstanceImpl broker = null;
	
	protected ClientRuntimeImpl() {
		super();
	}

	public static ClientRuntime getClientRuntimeImpl() {
		return MyInstance.runtimeImpl;
	}
	
	public boolean isEmbeddedBrokerRunning() {
		
		if (broker != null) {
			return broker.isBrokerRunning();
		} else {
			return false;
		}
	}
	
	public DirectBrokerConnection createDirectConnection() throws JMSException {
		 
		if (broker == null) {
			throw new JMSException ("Cannot create direct connection. No embedded broker running in this JVM.");
		}
		
		DirectBrokerConnection dbc = broker.createDirectConnection();	
		
		//ConnectionImpl.getConnectionLogger().info("ClientRuntime created direct connection ...");
		
		return dbc;
	}
	
	public synchronized BrokerInstance createBrokerInstance() throws ClassNotFoundException, 
	 IllegalAccessException, 
	 InstantiationException {
		
		if (broker == null) {
			broker = BrokerInstanceImpl.getInstance();
		} else if (broker.isShutdown()) {
			broker = new BrokerInstanceImpl();
		} else {
			throw new IllegalAccessException ("Cannot create broker instance.  A broker instance is already created.");
		}
		
		return broker;
	}
	
	/**
	 * Client runtime singleton instance is constructed here.
	 */
	private static class MyInstance {
		private final static ClientRuntime runtimeImpl = new ClientRuntimeImpl();
	}
}
