
# !page: admin_register
# !latest updated: 09Jul2021

from flask import request,  Blueprint, jsonify
from functions.code_generat_functions import otpGenerate
from functions.mail_functions import otpMail
from modules.database_modules import db_connect
from functions.date_time_functions import upload_time
from passlib.hash import pbkdf2_sha256  # for password encrytipn


# ? export blueprint section #################################################################################################################################

user_forgotpass_email = Blueprint("user_forgotpass_email", __name__, static_folder="static",
                                  template_folder="templates")

# ! Data base connection ######################################################################################################################
# * Copy the following three lines into all of the database connection required py files


# * function section #########################################################################################################################################


# * route section *******************************************************************************************************************************************


@user_forgotpass_email.route("/request-otp", methods=['POST'])
def requestFPOTP():
    header = request.headers
    authKey = header.get('Authorization')
    serverAuth = '88d464b2c2f13bcd7d1d648126e0e8aa5abeb5b1a209639f4e53d994696a422587b403fd69e1baa27b21deb03c2020fd3303e5cdc3ded8e0bc686b5dbbcd37ae'
    if request.method == 'POST' and authKey == serverAuth:
        con = db_connect()
        cur = con.cursor(dictionary=True, buffered=True)
        userMail = request.form['email']
        cur.execute(
            'select id from user_account where email=%s and account_type=%s', (userMail, 'email'))
        userInfo = cur.fetchone()
        if userInfo != None:
            genOTP = otpGenerate()
            datetime = upload_time()
            cur.execute(
                'delete from user_otp where user_id=%s and type=%s', (userInfo['id'], '2'))
            cur.execute('insert into user_otp (user_id, otp, type, datetime) values (%s,%s,%s,%s)',
                        (userInfo['id'], genOTP, '2', datetime))
            con.commit()
            otpMail(genOTP, userMail)
            con.disconnect()
            return jsonify({'message': 'password reset email is successfully sent', 'status': 'success'}), 200
        return jsonify({'message': 'email not found', 'status': 'fail'}), 404
    return jsonify({'message': 'unauthorized access'}), 403


@user_forgotpass_email.route("/verify-otp", methods=['POST'])
def verifyOTP():
    header = request.headers
    authKey = header.get('Authorization')
    serverAuth = '88d464b2c2f13bcd7d1d648126e0e8aa5abeb5b1a209639f4e53d994696a422587b403fd69e1baa27b21deb03c2020fd3303e5cdc3ded8e0bc686b5dbbcd37ae'
    if request.method == 'POST' and authKey == serverAuth:
        con = db_connect()
        cur = con.cursor(dictionary=True, buffered=True)
        userOtp = request.form['otp']
        email = request.form['email']

        cur.execute(
            'select id from user_account where email=%s and account_type=%s', (email, 'email'))
        userInfo = cur.fetchone()

        if userInfo != None:
            cur.execute(
                'select id,otp from user_otp where user_id=%s and type=%s', (userInfo['id'], '2'))
            userOTP = cur.fetchone()

            if userOtp != None:
                if str(userOtp) == str(userOTP['otp']):
                    cur.execute('delete from user_otp where id=%s',
                                (userOTP['id'],))
                    con.commit()
                    con.disconnect()
                    return jsonify({'email': email, 'message': 'you can change password now', 'status': 'success'}), 200
        return jsonify({'message': 'email not found', 'status': 'fail'}), 404
    return jsonify({'message': 'unauthorized access'}), 403


@user_forgotpass_email.route("/change-password", methods=['POST'])
def changePassword():
    header = request.headers
    authKey = header.get('Authorization')
    serverAuth = '88d464b2c2f13bcd7d1d648126e0e8aa5abeb5b1a209639f4e53d994696a422587b403fd69e1baa27b21deb03c2020fd3303e5cdc3ded8e0bc686b5dbbcd37ae'
    if request.method == 'POST' and authKey == serverAuth:
        con = db_connect()
        cur = con.cursor(dictionary=True, buffered=True)
        email = request.form['email']
        password = pbkdf2_sha256.hash(request.form['password'])
        cur.execute(
            'select id from user_account where email=%s and account_type=%s', (email, 'email'))
        userInfo = cur.fetchone()
        if userInfo != None:
            cur.execute(
                'update user_account set password=%s where id=%s', (password, userInfo['id']))
            con.commit()
            con.disconnect()
            return jsonify({'message': 'your password is successfully changed', 'status': 'success'}), 200
        return jsonify({'message': 'email not found', 'status': 'fail'}), 404
    return jsonify({'message': 'unauthorized access'}), 403
# *************************************************************************************************************************************************
