import datetime
from datetime import date, timedelta
from pymongo import MongoClient,errors
from configparser import ConfigParser
import pika
import json

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"]
EVE_DATE_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'

#RabbitMQ connection credentials
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='fanout', durable=True)
    channel.exchange_declare(exchange=exchange_name, exchange_type='direct', durable=True)
    route_key = queue_name = 'demographic_requests_PROD'
    channel.queue_bind(exchange=exchange_name, queue=queue_name, routing_key=route_key)
except Exception as channel_declaration:
    print(channel_declaration)
    

def mongoInsertOperator(data):
    response_code = 0
    try:
        mongo_url = "mongodb://acsuser:Acnts#Acs*2020@DL-R2-SDB01.digilocker.gov.in,DL-R2-MDB01.digilocker.gov.in,DL-SlaveDB-04.digilocker.gov.in/accounts_services?replicaSet=rsdb4&connectTimeoutMS=5000&socketTimeoutMS=5000"
        crud_operation = "C"
        data_value = data
        db_name = "accounts_services"
        mongo_collection_name = "demographic_requests_data"
        uri_value = 'd'
        try:
            response_code = 1
            if crud_operation == 'C':
                mongo_client = MongoClient(mongo_url)
                mongo_client[db_name][mongo_collection_name].insert_one(data_value)
                return {'status':True, 'msg':(response_code, 'Success'), 'code':response_code}
        except errors.DuplicateKeyError as duplicaterror:
            response_code = 2
            return {'status':False, 'msg':"Duplicate error as %s"%duplicaterror, 'code':response_code }
        except Exception as Crudexception:
            response_code = 3
            if 'document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping' in Crudexception:
                errr = ("BSON error: %s")%Crudexception
                return {'status':False, 'msg':errr, 'code':response_code}
            else:
                response_code = 5
                return {'status':False, 'msg':Crudexception, 'code':response_code, 'uri': uri_value}
    except Exception as JSONError:
        err = ("Data error as %s")%JSONError
        return {'status':False, 'msg':err, 'code':response_code}

def callback(ch, method, properties, body):
    try:
        data = json.loads(body)
        content = data
        try:
            '''
            {"name":"Dilbar","dob":"2017-06-15",
            "gender":"M","uid":"467696261503","mobileno":"8104244803",
            "email":null,"created_on":{"$date":"2021-08-30T15:14:38.000Z"},"consent":"Y"}'''

            created_on = content['created_on']['$date']
            content['created_on'] = created_on
            insert_data_mongo = mongoInsertOperator(content)
            ch.basic_ack(delivery_tag=method.delivery_tag,multiple=False)

        except Exception as flowExpn:
            ch.basic_reject(delivery_tag=method.delivery_tag, requeue=True)
            print('flowExpn')
            print(flowExpn)
    except Exception as data_expn:
        ch.basic_reject(delivery_tag=method.delivery_tag, requeue=True)

channel.basic_qos(prefetch_count= int(100))

try:
    b = channel.basic_consume(queue=queue_name, on_message_callback = callback)
    channel.start_consuming()
except Exception as ChannelException:
    print(ChannelException)
    print('Unable to communicate with RMQ')
    channel.stop_consuming()