package omq.common.event;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;

import omq.common.remote.RevoConnectionFactory;
import omq.common.util.RevoEnvironment;
import omq.common.util.Serializer;
import omq.exception.EnvironmentException;
import omq.exception.SerializerException;


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

/**
 * This class is used to publish events into a topic
 * 
 * @author Sergi Toda <sergi.toda@estudiants.urv.cat>
 * 
 */
public class EventTrigger {
	private static EventTrigger trigger;
	private static Connection connection;
	private static Channel channel;

	private EventTrigger(Properties env) throws IOException, KeyManagementException, NoSuchAlgorithmException {
		connection = RevoConnectionFactory.getConnection(env);
		channel = connection.createChannel();
	}

	public static void initEventTrigger(Properties env) throws EnvironmentException, Exception {
		if (trigger == null) {
			trigger = new EventTrigger(env);
		}
	}

	public static void initEventTrigger() throws EnvironmentException, Exception {
		if (trigger == null) {
			trigger = new EventTrigger(RevoEnvironment.getEnvironment());
		}
	}

	public static synchronized void publish(String topic, Object obj) throws IOException, SerializerException {
		Event event = new Event(topic, obj);
		channel.exchangeDeclare(topic, "fanout");
		channel.basicPublish(topic, "", null, Serializer.serialize(event));
	}

	public static synchronized void publish(String topic, Event event) throws IOException, SerializerException {
		channel.exchangeDeclare(topic, "fanout");
		channel.basicPublish(topic, "", null, Serializer.serialize(event));
	}

	public static void close() throws Exception {
		trigger = null;
		channel.close();
		connection.close();
	}
}
