# RabbitMQ producer for processes_created event
# s. also https://medium.com/@mansha99/microservices-in-python-django-rabbitmq-and-pika-fe1adb0c6a1a

import json
import pika

# django settings
from django.conf import settings

ROUTING_KEY = "processes.created.key"
EXCHANGE = "processes_exchange"
THREADS = 5


class ProducerProcessesCreated:
    def __init__(self) -> None:
        # hearbeat = 600 indicates that after 600 seconds
        # the peer TCP connection should be considered unreachable
        #  by RabbitMQ and client libraries
        #
        # blocked_connection_timeout=300 means after 300 seconds
        # the peer TCP connection is interrupted and dropped.

        common_params = pika.ConnectionParameters(settings.RABBITMQ_HOST, heartbeat=600, blocked_connection_timeout=300)
        self.connection = pika.BlockingConnection(common_params)
        self.channel = self.connection.channel()

        # self.channel.exchange_declare(exchange=EXCHANGE, exchange_type='direct')
        self.channel.queue_declare(queue=ROUTING_KEY, durable=True)

    # This method will be called inside view for sending RabbitMQ message
    # method here is same as properties.content_type in listener callback
    def publish(self, method, body):
        print("Inside ProcessesService: Sending to RabbitMQ: ")
        print(body)
        properties = pika.BasicProperties(method)
        self.channel.basic_publish(
            exchange=EXCHANGE, routing_key=ROUTING_KEY, body=json.dumps(body), properties=properties
        )

    def close(self):
        self.connection.close()
        print("Connection closed")
