package eu.dnetlib.social.producer;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;

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

import eu.dnetlib.social.SocialUploadable;

/**
 * This class is the producer that puts messages in the queue depending on the value of targetSite property of the
 * SocialUploader object.
 * 
 * @author alessia
 * 
 */
public class SocialEnqueuer {

	private static final Log log = LogFactory.getLog(SocialEnqueuer.class);

	private ConnectionFactory connectionFactory;

	public void produce(final SocialUploadable object) throws IOException {
		String queueName = object.getTargetSite();
		log.debug("Sending object on " + queueName + " queue");
		JSONObject o = object.toJSONSimple();
		String jsonString = o.toString();
		log.debug("Jsoned object = " + jsonString);
		Connection conn = connectionFactory.newConnection();
		Channel chan = conn.createChannel();
		/*
		 * queueDeclare(java.lang.String queue, boolean durable, boolean exclusive, boolean autoDelete,
		 * java.util.Map<java.lang.String,java.lang.Object> arguments) Declare a queue.
		 */
		chan.queueDeclare(queueName, true, false, false, null);
		chan.basicPublish("", queueName, null, jsonString.getBytes());
		System.out.println(" [x] Sent " + jsonString);
		chan.close();
		conn.close();

	}

	public void setConnectionFactory(final ConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	public ConnectionFactory getConnectionFactory() {
		return connectionFactory;
	}
}
