package omq.common.remote;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import omq.common.util.OmqConnectionFactory;

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

/**
 * 
 * @author Sergi Toda <sergi.toda@estudiants.urv.cat> 
 *
 */
//TODO aquesta classe es pot eliminar
public abstract class RemoteListener extends Thread {
	private static String defaultXml = "eventListener.xml";

	protected Connection connection;
	protected Channel channel;
	protected QueueingConsumer consumer;
	protected boolean killed = false;

	protected RemoteListener() throws Exception {
		// Load the default environment
		FileInputStream fis = new FileInputStream(defaultXml);
		Properties env = new Properties();
		env.loadFromXML(fis);
		fis.close();

		startConnection(env);
	}

	protected RemoteListener(Properties env) throws Exception {
		startConnection(env);
	}

	private void startConnection(Properties env) throws Exception {
		connection = OmqConnectionFactory.getNewConnection(env);
		channel = connection.createChannel();
	}

	public synchronized Channel getChannel() throws Exception {
		return connection.createChannel();
	}

	/**
	 * Interrupt and kill the Thread
	 * 
	 * @throws IOException
	 */
	public void kill() throws IOException {
		interrupt();
		killed = true;
		channel.close();
		connection.close();
	}

	/**
	 * TODO RESTART CONNECTION FAULT TOLERANCE
	 */

}
