package com.sagacloud.broadcast;

import com.rabbitmq.client.*;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.sagacloud.cache.cachedObject.QueryObjects;
import com.sagacloud.utils.OssUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeoutException;

/**
 * Created by wo on 10/22/19.
 */
public class RabbitMsgHandler implements MsgHandler{
    private  ConnectionFactory factory;
    private  Connection connection;
    private  Channel channel;
    private  String topic;
    private  String routingKey;
    private static final Logger log = LoggerFactory.getLogger(RabbitMsgHandler.class);

    public  void init() {
        factory = new ConnectionFactory();
        factory.setUsername(OssUtils.getProperty("rabbit.userName"));
        factory.setPassword(OssUtils.getProperty("rabbit.password"));
        factory.setHost(OssUtils.getProperty("rabbit.host"));
        factory.setPort(Integer.parseInt(OssUtils.getProperty("rabbit.port")));
        factory.setVirtualHost(OssUtils.getProperty("rabbit.virtualhost"));
        topic = OssUtils.getProperty("rabbit.topic");
        routingKey = OssUtils.getProperty("rabbit.routingKey");
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(topic, "topic", true);
            this.consume();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public  void publish(String msg) {
        try {
            channel.basicPublish(topic, routingKey, null, msg.getBytes(Charset.forName("UTF-8")));
        } catch (IOException e) {
            log.error("",e);
        }

    }

    public  void consume(){
        try {
            String queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, topic, routingKey);
            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                log.debug("Received message: " + message);
                MsgHandler.clearCache(message);
                QueryObjects.clearCache(message);
            };
            channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static void main(String[] args){
        RabbitMsgHandler h = new RabbitMsgHandler();
        h.init();
        for(int i = 0; i < 5; i++)
            h.publish("Here I am!");
    }
}
