'''
Author: Abhijeet Anand
Email: abhijeet.anand@digitalindia.gov.in
Dated: 17/10/2021
Purpose: Function to send and verify otp
Given by: Alok Ranjan sir
Task ID: 20111 
'''
import os

from dotenv import load_dotenv
import random
from datetime import datetime
from lib.redislib import RedisLib
# from lib.smslib import SmsLib
from lib import smslib
SmsLib = smslib.SmsLib()

load_dotenv()
MAX_CONTENT_LENGTH = os.getenv('MAX_CONTENT_LENGTH')

'''Constants'''
CURRENT_D_FORMAT_YMDHIS = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
CURRENT_D_YMDHIS = datetime.now().strftime('YmdHMS')
redis_ttl = os.getenv('REDIS_KEY_TTL')


class OTP_services:
    def __init__(self):
        self.rs = RedisLib()

    def send_mobile_otp(self, mobile):
        try:
            otpdetail = self.generateotp(mobile)
            print('2------------------', otpdetail)
            if otpdetail and otpdetail['status'] == True:
                app_message = str(otpdetail['data_sms']['otp']) + ' is your OTP to access DigiLocker. OTP is confidential and valid for 10 minutes. For security reasons, DO NOT share this OTP with anyone.'
                print('1------------------', app_message)
                self.rs.set(key = str(mobile)+'_family_otp', value =  otpdetail['data_sms']['otp'], ex=redis_ttl)
                self.rs.set(key = 'otp_generated_time_'+str(mobile), value =  CURRENT_D_FORMAT_YMDHIS, ex=redis_ttl)
                response = SmsLib.send_message(otpdetail['data_sms']['mobileno'], app_message, 'otpmsg', os.getenv('NIC_SMS_OTP_TEMPLATE_ID'))
                print('5------------------', response)
                return {'status': response['status'], 'msg': 'Please enter One Time Password (OTP) sent on your mobile number.',
                        'otp': otpdetail['data_sms']['otp']}
            else:
                return {"status": "error", "error_description": "Some technical error occured!"}
        except Exception as e:
            print(str(e))
            return {"status": "error", "error_description": str(e)}

    def generateotp(self, mobile):
        try:
            six_digit_random_number = random.randrange(100000, 999999)
            time = CURRENT_D_FORMAT_YMDHIS
            data_sms = {}
            #get otp from redis if alreday exists
            redis_data = self.rs.get(key = str(mobile)+'_family_otp')
            print('1------------------', redis_data)
            if redis_data and redis_data != None:
                data_sms['mobileno'] = mobile
                data_sms['otp'] = redis_data
                data_sms['otp_generated_time'] = self.rs.get(key = 'otp_generated_time_'+str(mobile))
                data_sms['otp_generated_from'] = 'redis'
                return {'status': True, 'data_sms': data_sms}
            else:    
                data_sms['mobileno'] = mobile
                data_sms['otp'] = six_digit_random_number
                data_sms['otp_generated_time'] = time
                data_sms['otp_generated_from'] = 'new'
                return {'status': True, 'data_sms': data_sms}
        except Exception as e:
            print(str(e))
            return {"status": "error", "error_description": str(e)}

    def verify_mobile_otp(self, mobile, otp):
        try:
            redis_data = self.rs.get(key= str(mobile)+'_family_otp')
            if redis_data ==otp:
                # once otp verified, remove data from redis
                self.rs.remove(key= str(mobile)+'_family_otp')
                self.rs.remove(key = 'otp_generated_time_'+str(mobile))
                return {'status':'success','success_description':'OTP successfully verified.'}
            else:
                return {'status':'error','error_description':'Please enter correct OTP.'}
        except Exception as e:
            print(str(e))
            return {"status": "error", "error_description": str(e)}