from django.conf import settings
from contextlib import contextmanager
import pika
import json


@contextmanager
def rabbit_connection():
    connection = pika.BlockingConnection(pika.ConnectionParameters(**settings.RABBIT))

    try:
        yield connection.channel()
    except Exception as e:
        connection.close()
        raise e


class Rabbit(object):
    queues_declares = []

    def send(self, data, queue, force=False, queue_args=None):
        with rabbit_connection() as server:
            if not force:
                self.declare_queue(name=queue, queue_args=queue_args)
            server.basic_publish(routing_key=queue, body=json.dumps(data), exchange="")

    def declare_queue(self, name, connection=None, queue_args=None):
        if queue_args is None:
            queue_args = {}
        if name not in self.queues_declares:
            self.queues_declares.append(name)
            if not connection:
                with rabbit_connection() as mq_connection:
                    mq_connection.queue_declare(queue=name, durable=True, arguments=queue_args)
            else:
                connection.queue_declare(queue=name, durable=True, arguments=queue_args)


rabbit = Rabbit()
