package omq.common.broker;

import java.util.Properties;

import omq.Remote;
import omq.client.proxy.Proxymq;
import omq.client.remote.response.ResponseListener;
import omq.common.remote.OmqConnectionFactory;
import omq.common.util.Environment;
import omq.exception.EnvironmentException;
import omq.exception.RemoteException;
import omq.server.remote.request.RemoteObject;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

public class Broker {
	private static Connection connection;
	private static Channel channel;

	public static void initBroker(Properties env) throws Exception {
		try {
			Environment.getEnvironment();
		} catch (EnvironmentException ex) { // environment not set.
			Environment.setEnvironment(env);
			connection = OmqConnectionFactory.getConnection(env);
			channel = connection.createChannel();
		}
	}

	// TODO: what happens if the connection is not set
	public static Connection getConnection() throws Exception {
		return connection;
	}

	public static Channel getChannel() throws Exception {
		return channel;
	}

	public static Remote lookup(String reference, Class<?> contract) throws RemoteException {
		try {
			Properties environment = Environment.getEnvironment();

			if (ResponseListener.isVoid()) {
				ResponseListener.init(environment);
			}
			if (!Proxymq.containsProxy(reference)) {
				Proxymq proxy = new Proxymq(reference, contract, environment);
				Class<?>[] array = { contract };
				return (Remote) Proxymq.newProxyInstance(contract.getClassLoader(), array, proxy);
			}
			return (Remote) Proxymq.getInstance(reference);

		} catch (Exception e) {
			throw new RemoteException(e);
		}
	}

	public static void bind(String reference, RemoteObject remote) throws RemoteException {
		try {
			Properties environment = Environment.getEnvironment();
			remote.start(reference, environment);
		} catch (Exception e) {
			throw new RemoteException(e);
		}
	}

	public static void unbind(String reference) throws RemoteException {

	}

	public void rebind(String name, Remote obj) throws RemoteException {

	}

}
