# sending logs to a queue
import pika,json,os
from dotenv import load_dotenv

load_dotenv() 

# initialize the logs carrier
logs = [] 

def logger(queue,log):
    logs.append(log)  
    try:  
        if(log == None):
            response = {"status":"error","msg":"input error"} 
            return response 
        json_data = log
        res = send_to_queue(queue,'direct',json_data)
        print(res) 
        if res['status'] == "success":
            logs.pop(0)
        else:
            print("Logs not working, kindly check...")
    except Exception as loggingException:
        response = {'status':"failed", 'err_code':999, 'msg': loggingException}
        return response

def send_to_queue(queue_name,exchange_type,log_data):
    try:
        ''' rmq connection ''' 
        
        exchange_name = os.getenv('EXCHANGE_NAME')
        
        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=exchange_type, durable=True)
            accounts_channel.basic_publish(exchange = exchange_name, routing_key = queue_name,
                                    body = json.dumps(log_data))
            accounts_channel.close()
            response = {"status":"success", 'msg': 'Request sent to queue'}
            return response
        except Exception as logException:
            response = {"status":"error", 'msg': logException} 
            return response 
    except Exception as e: 
        return {"status": "error", "error_description": "error in account nominee function" + str(e)}