import pika, json, os
from dotenv import load_dotenv

load_dotenv()

CONNECTION_ERROR = 'Connection Error!'
DELIVERY_MODE = 'delivery_mode'
DIRECT = 'direct'
FANOUT = 'fanout'
EXPIRATION = 'expiration'
STATUS = 'status'

class RabbitMQAccounts:
   
    def account_nominee(fields):
        try:
            ''' insert data to rmq queue '''
            
            if(fields == None):
                response = {STATUS:0,"msg":"input error"}
                return response
            
            message = {"data":fields, DELIVERY_MODE:2}
            exchange_name = os.getenv('EXCHANGE_NAME')
            # RabbitMQ connection credentials
            try:
                credentials = pika.PlainCredentials(os.getenv('RABBITMQ_ACCOUNTS_USERNAME'), os.getenv('RABBITMQ_ACCOUNTS_PASSWORD'))
                parameters = pika.ConnectionParameters(os.getenv('RABBITMQ_ACCOUNTS_HOST'),
                                                os.getenv('RABBITMQ_ACCOUNTS_PORT'),os.getenv('RABBITMQ_ACCOUNTS_VHOST'),
                                                credentials,
                                                socket_timeout= 300)
                connection = pika.BlockingConnection(parameters)
                accounts_channel = connection.channel()
                accounts_channel.exchange_declare(exchange=exchange_name, exchange_type=FANOUT, durable=True)
                accounts_channel.basic_publish(exchange = exchange_name, routing_key = '',
                                        body = json.dumps(message))
                accounts_channel.close()
                response = {STATUS:1, 'msg': 'Request sent to queue'}
                return response
            except Exception as logException:
                response = {STATUS:0, 'msg': logException}
                return response
        except Exception as e:
            return {"status": "error in account nominee function", "error_description": str(e)}
                     