package omq.common.util;

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

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

/**
 * 
 * @author Sergi Toda <sergi.toda@estudiants.urv.cat>
 * 
 */
public class OmqConnectionFactory {
	private static Connection connection;

	public static void init(Properties env) throws KeyManagementException, NoSuchAlgorithmException, IOException {
		if (connection == null) {
			connection = getNewConnection(env);
		}
	}

	public static Connection getNewConnection(Properties env) throws IOException, KeyManagementException, NoSuchAlgorithmException {
		// Get login info of rabbitmq
		String username = env.getProperty(ParameterQueue.USER_NAME);
		String password = env.getProperty(ParameterQueue.USER_PASS);

		// Get host info of rabbimq (where it is)
		String host = env.getProperty(ParameterQueue.SERVER_HOST);
		int port = Integer.parseInt(env.getProperty(ParameterQueue.SERVER_PORT));

		boolean ssl = Boolean.parseBoolean(env.getProperty(ParameterQueue.ENABLE_SSL));

		// Start a new connection and channel
		ConnectionFactory factory = new ConnectionFactory();
		factory.setUsername(username);
		factory.setPassword(password);
		factory.setHost(host);
		factory.setPort(port);
		if (ssl) {
			factory.useSslProtocol();
		}
		return factory.newConnection();
	}

	public static Channel getNewChannel() throws IOException {
		return connection.createChannel();
	}
}
