'''
Created on 05-Oct-2020
-- to set the call for upsert operation

@author: Saurabh Kumar Pandey
This script is the worker which aims at performing the attempts log of user
'''
#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 = 'Create_User_Xchange'    
    channel.exchange_declare(exchange=exchange_name, exchange_type='direct', durable=True)
    route_key = queue_name = 'User_Attempts_Log_'+ application_environment 
    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 updateUserProfile(ch, method, properties, content, log_id):
    global userMongoData, refkey
    userProfileMongoData = {}
    try:    
        if content.get('transactionid') != None:        
            try:
                now = datetime.datetime.now()
                userProfileMongoData['transactionid'] = content['transactionid']
                
                if content.get('name') != None:    
                    userProfileMongoData['name'] = content['name']
                if content.get('dob') != None:
                    dob = datetime.datetime.strptime(content['dob'], '%Y-%m-%d')   
                    userProfileMongoData['dob'] = dob
                if content.get('gender') != None:    
                    userProfileMongoData['gender'] = content['gender']
                if content.get('mobile') != None:    
                    userProfileMongoData['mobile'] = content.get('mobile')
                if content.get('email') != None:    
                    userProfileMongoData['email'] = content.get('email')
                if content.get('uid') != None:
                    userProfileMongoData['uid'] = content.get('uid')                 
                if content.get('uid_token') != None:
                    userProfileMongoData['uid_token'] = content.get('uid_token')               
                if content.get('pin') != None:
                    userProfileMongoData['pin'] = content.get('pin')             
                if content.get('user_alias') != None:
                    userProfileMongoData['user_alias'] = content.get('user_alias')
                
                if content.get('source') != None:
                    userProfileMongoData['source'] = content.get('source')                
                if content.get('data_directory_type') != None:
                    userProfileMongoData['data_directory_type'] = content.get('data_directory_type')                    
                if content.get('user_type') != None:
                    userProfileMongoData['user_type'] = content.get('user_type')                                                        
                userProfileMongoData['last_updated_on'] = now          
                    
                try:
                    dataUpdUser = { "operation": "U",
                        "db": accounts_db["accounts_db"],
                        "collection":'users_signup_attempts_log',
                        "data": userProfileMongoData,
                        "key": {'transactionid':content['transactionid']},
                        "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_ack(delivery_tag=method.delivery_tag,multiple=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 = updateUserProfile(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['users-signup-attempts']))         
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()
