package com.jasamedika.medifirst2000.notification.impl;

import java.io.IOException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jasamedika.medifirst2000.notification.MessageSubscriber;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

@Component("messageSubscriber")
public class MessageSubscriberImpl implements MessageSubscriber {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(MessageSubscriberImpl.class);

	Channel channel;
	Connection connection;
	AMQP.Queue.DeclareOk Queue;

	@Autowired
	DataSource dataSource;

	public void startRabbitMQNotification(String host, String routingKeyAndQueueName) throws Exception {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(host);
		connection = factory.newConnection();
		channel = connection.createChannel();
		Queue = channel.queueDeclare(routingKeyAndQueueName, true, false, false, null);
	}

	public void listenRabbitMQNotification(String routingKeyAndQueueName, Consumer consumer, boolean autoAck)
			throws Exception {
		for (int i = 0; i < Queue.getMessageCount(); i++) {
			channel.basicConsume(routingKeyAndQueueName, autoAck, consumer);
		}

	}

	public void stopRabbitMQNotification() throws Exception {
		channel.close();
		connection.close();
	}

	public Consumer getDefaultConsumer() {
		return new DefaultConsumer(channel) {

			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {
				LOGGER.info(new String(body, "UTF-8"));
				getChannel().basicAck(envelope.getDeliveryTag(), false);
			}
		};
	}
}
