'''
Created on Jun 12, 2020

@author Saurabh Kumar Pandey
'''
import pika
import json
import logging
from configparser import ConfigParser

config_object = ConfigParser()
config_object.read("/opt/rmq-workers/config.ini")
import time

class userFailureLogger:
    #return True 
    global userFailureLogger
    
    def __init__(self):  
#         if cfg.log_transactions.get('active') != 'YES':
#             return {'status': False, 'msg': 'SET CONFIG TO WRITE LOGS'}
        
        try:   
            self.exchange='Create_User_Xchange'
            self.routing_key='User_Creation_Log_'+ cfg.application_environment
            self.credentials = pika.PlainCredentials(cfg.rabbitmq['username'], cfg.rabbitmq['password'])
            self.parameters = pika.ConnectionParameters(cfg.rabbitmq['host'], cfg.rabbitmq['port'], cfg.rabbitmq['vhost'], self.credentials)                                   
            
            #Connection to a broker on the local machine
            self.connection = pika.BlockingConnection(self.parameters)
            self.channel = self.connection.channel()
#             self.channel.exchange_declare(exchange=exchange_name, exchange_type='direct', durable=True)
#             self.dbConf = {"db": cfg.log_transactions["db"],
#                            "collection":cfg.log_transactions["collection"]}
            
        except Exception as initExcn:
            print(initExcn)
            
    def writeLogFile(self, user_type, log_data, **kwargs):
        try:            
            timestr = time.strftime("%Y%m%d") # -%H%M%S
            log_file_path = cfg.log_transactions["log_file_path"] + user_type + '-' + timestr +'-error.log'
                
            logging.basicConfig(filename=log_file_path, filemode='w', format='%(name)s - %(levelname)s - %(message)s')        
            logging.warning(str(log_data))
            
        except Exception as basic_excn:
            print(basic_excn)
        finally:
            return True      
    
    def logRes(self, log_id='NA', user_type='NA', log_data='NA', source='Mongo', **kwargs):
        if cfg.log_transactions["active"] != 'YES':
           return {'status': True, 'msg': 'PLZ UPDATE CONFIG FOR LOGS'} 
        try:
            data = {  
                    "data": log_data,
                    "log_id" : log_id,
                    "request_type": user_type,
                    'source': source
                } 
            try:           
                message = json.dumps(data)
            except Exception as jsonException:
                data = {  
                    "data": {'excpn': str(log_data)},
                    "log_id" : log_id,
                    "request_type": user_type,
                    'source': source
                }                
                
                message = json.dumps(data)   
#                 self.writeLogFile(user_type, str(log_data))
                
            self.channel.basic_publish(exchange=self.exchange,
                              routing_key=self.routing_key,
                              body= message,
                              properties=pika.BasicProperties(
                              delivery_mode = 2
                              ))  
            return {'status': True, 'msg': 'toFailureQueue'}
        except Exception as setError:
#             self.writeLogFile(user_type, (log_data, setError))
            return {'status': False, 'msg': setError}  