'''
Created on 18-Mar-2021
-- to set the call for upsert operation

@author: Saurabh Kumar Pandey
This script is for nominee operations
Account_Nominee_Xchange
Account_Nominee_DELHI
Account_Nominee_PUNE

'''
#Standard library import
#this will pull the demographic details from Queue and publish it to the MYSQL or mongodb user linking
import pika,json,datetime,uuid
from datetime import date, timedelta
from lib.create_user_mysql_mongo import mongoUpsertOperator
from lib.log import logger
from configparser import ConfigParser 

config_object = ConfigParser()
config_object.read("/opt/rmq-workers/config.ini") 
rabbitmq = config_object["rabbitmq"]
application_environment = config_object["environment"]['application']
application_location = config_object["environment"]['location']
prefetch_counter = config_object["prefetch_count"]
accounts_db = config_object["mongo_accounts_db"]

#RabbitMQ connection credentials

#Connection to a broker on the local machine
try:
    credentials = pika.PlainCredentials(rabbitmq['username'], rabbitmq['password'])
    parameters = pika.ConnectionParameters(rabbitmq['host'], rabbitmq['port'], rabbitmq['vhost'], credentials, socket_timeout=int(rabbitmq['socket_timeout']))                                  

    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()    
    exchange_name = 'Account_Nominee_Xchange'    
    channel.exchange_declare(exchange=exchange_name, exchange_type='fanout', durable=True)
    route_key = queue_name = 'Account_Nominee_'+ application_location 
    channel.queue_bind(exchange=exchange_name, queue=queue_name, routing_key=route_key)
except Exception as channel_declaration:
    print(channel_declaration)  
    response = {'channel_exception': 'Unable to connect to RMQ', 'msg': channel_declaration}
    logger('accounts_worker_log',response)  
            
def updateNominee(ch, method, properties, content, log_id):
    global userMongoData, refkey
    nominee_data = {}
    try:    
        if content.get('nominee_id') != None:        
            try:
                now = datetime.datetime.now()    
#                nominee_data['username'] = content['username']         
                if content.get('created_on') != None:
                    nominee_data['created_on'] = now 
                             
                if content.get('name') != None:    
                    nominee_data['name'] = content['name']
                if content.get('username') != None:
                    nominee_data['username'] = content.get('username')     
                if content.get('dob') != None:
                    dob = datetime.datetime.strptime(content['dob'], '%Y-%m-%d')   
                    nominee_data['dob'] = dob
                if content.get('gender') != None:    
                    nominee_data['gender'] = content['gender']
                if content.get('relation') != None:    
                    nominee_data['relation'] = content['relation']
                if content.get('uid') != None:    
                    nominee_data['uid'] = content['uid']       
                if content.get('uid_token') != None:
                    nominee_data['uid_token'] = content.get('uid_token')         
                if content.get('mobileno') != None:    
                    nominee_data['mobileno'] = content.get('mobileno')
                if content.get('email') != None:    
                    nominee_data['email'] = content.get('email')           
                if content.get('photo') != None:
                    nominee_data['photo'] = content.get('photo')   
                                  
                if content.get('is_deleted') != None:
                    nominee_data['is_deleted'] = content.get('is_deleted')    
                    nominee_data['deleted_on'] = now   
                                                                     
                nominee_data['modified_on'] = now   
                    
                try:
                    dataUpdUser = { "operation": "U",
                        "db": accounts_db["accounts_db"],
                        "collection":'account_nominee',
                        "data": nominee_data,
                        "key": {'nominee_id':content['nominee_id']},
                        "multi":'N'}
    
                    mongorespProfile = mongoUpsertOperator(dataUpdUser)
                    print(mongorespProfile)
                    
                    if mongorespProfile['status'] == True and mongorespProfile['code'] == 1: 
                        ch.basic_ack(delivery_tag=method.delivery_tag,multiple=False)
                        return {'status': True, 'msg' : 'UserUpated'}               
                      
                    elif mongorespProfile['status'] == False:
                        if mongorespProfile['code']  in {2, 3, 0 }: 
                            ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False) 
                    else:
                        ch.basic_reject(delivery_tag=method.delivery_tag, requeue=True) 
                        return {'status': False, 'msg' : ('profileWrite', 'error 217')}
                except Exception as rmqPublishError:
                    ch.basic_reject(delivery_tag=method.delivery_tag, requeue=True) 
                    return {'status':False, 'msg':rmqPublishError}
                         
            except Exception as dataError:
                ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False) 
                return {'status':False, 'msg':dataError}   
        else:            
            ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False)
            return {'status': False, 'msg' : 'digilockerid not defined'}
                 
    except Exception as dataError:
        ch.basic_reject(delivery_tag=method.delivery_tag, requeue=True) 
        return {'status':False, 'msg':dataError}       

def callback(ch, method, properties, body):
    try:    
        data = json.loads(body)   
        content = data.get('data')
        log_id = data.get('id') or None    
        resp = updateNominee(ch, method, properties, content, log_id)
        print(resp)            
    except Exception as functinal_expn:
        print(functinal_expn)
        ch.basic_reject(delivery_tag=method.delivery_tag, requeue=True)        
                
channel.basic_qos(prefetch_count=int(prefetch_counter['accounts-nominee']))         
try: 
    b = channel.basic_consume(queue=queue_name, on_message_callback = callback)
    channel.start_consuming()   
except Exception as ChannelException:
    print(ChannelException)   
    response = {'channel_exception': 'Unable to connect to RMQ', 'msg': ChannelException}
    logger('accounts_worker_log',response) 
    channel.stop_consuming() 