
# !page: user_profile
# !latest updated: 02Nov2022

from flask import render_template, request,  Blueprint, jsonify
from modules.database_modules import db_connect
from passlib.hash import pbkdf2_sha256  # for password encryption
import datetime as dt
from htmlmin.minify import html_minify

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


@user_webview_profile.route("/", methods=['GET'])
def profileView():
    header = request.headers
    authKey = header.get('Authorization')
    serverAuth = '88d464b2c2f13bcd7d1d648126e0e8aa5abeb5b1a209639f4e53d994696a422587b403fd69e1baa27b21deb03c2020fd3303e5cdc3ded8e0bc686b5dbbcd37ae'
    userID = header.get('xtenId')
    # userID = 13
    if authKey == serverAuth:
        con = db_connect()
        cur = con.cursor(dictionary=True, buffered=True)
        cur.execute(
            "select id, name, phone, email, account_type, img_path from user_account where id=%s", (userID,))
        userAccountInfo = cur.fetchone()
        cur.execute(
            'select birth_date, birth_day, birth_time, gender from user_info where user_id=%s', (userID,))
        userInfo = cur.fetchone()
        return html_minify(render_template('userprofile_webview_port.html', scriptTitle='Profile',
                                           userData={
                                               'id': userAccountInfo['id'],
                                               'name': userAccountInfo['name'],
                                               'birth_date': userInfo['birth_date'],
                                               'birth_day': userInfo['birth_day'],
                                               'birth_time': userInfo['birth_time'],
                                               'gender': userInfo['gender'],
                                               'phone': userAccountInfo['phone'],
                                               'email': userAccountInfo['email'],
                                               'imgPath': userAccountInfo['img_path'],
                                               'account_type': userAccountInfo['account_type']
                                           }))
    return jsonify({'message': 'forbidden access'}), 403


@user_webview_profile.route('/get-canceled-data', methods=['POST'])
def getCancelData():
    header = request.headers
    authKey = header.get('Authorization')
    serverAuth = '88d464b2c2f13bcd7d1d648126e0e8aa5abeb5b1a209639f4e53d994696a422587b403fd69e1baa27b21deb03c2020fd3303e5cdc3ded8e0bc686b5dbbcd37ae'
    if authKey == serverAuth:
        con = db_connect()
        cur = con.cursor(dictionary=True, buffered=True)
        userID = request.form['userID']
        reqType = request.form['reqType']
        if reqType == 'name':
            cur.execute('select name from user_account where id=%s', (userID,))
            userData = cur.fetchone()['name']
            return jsonify({'userID': userID, 'reqType': reqType, 'userData': userData})
        elif reqType == 'bdate':
            cur.execute(
                'select birth_date from user_info where user_id=%s', (userID,))
            userData = cur.fetchone()['birth_date']
            return jsonify({'userID': userID, 'reqType': reqType, 'userData': str(userData)})
        elif reqType == 'btime':
            cur.execute(
                'select birth_time from user_info where user_id=%s', (userID,))
            userData = cur.fetchone()['birth_time']
            return jsonify({'userID': userID, 'reqType': reqType, 'userData': str(userData)})
        elif reqType == 'gender':
            cur.execute(
                'select gender from user_info where user_id=%s', (userID,))
            userData = cur.fetchone()['gender']
            return jsonify({'userID': userID, 'reqType': reqType, 'userData': userData})
        elif reqType == 'email':
            cur.execute(
                'select email from user_account where id=%s', (userID,))
            userData = cur.fetchone()['email']
            return jsonify({'userID': userID, 'reqType': reqType, 'userData': userData})
        elif reqType == 'phone':
            cur.execute(
                'select phone from user_account where id=%s', (userID,))
            userData = cur.fetchone()['phone']
            return jsonify({'userID': userID, 'reqType': reqType, 'userData': userData})
    return jsonify({"message": 'forbidden access', 'status': 'failed'}), 403


@user_webview_profile.route('/update-data', methods=['POST'])
def updateData():
    header = request.headers
    authKey = header.get('Authorization')
    serverAuth = '88d464b2c2f13bcd7d1d648126e0e8aa5abeb5b1a209639f4e53d994696a422587b403fd69e1baa27b21deb03c2020fd3303e5cdc3ded8e0bc686b5dbbcd37ae'
    if authKey == serverAuth:
        con = db_connect()
        cur = con.cursor(dictionary=True, buffered=True)
        userID = request.form['userID']
        reqType = request.form['reqType']
        userData = request.form['userData']
        if reqType == 'name':
            cur.execute(
                'update user_account set name=%s where id=%s', (userData, userID))
            con.commit()
            con.disconnect()
            return jsonify({'userID': userID, 'reqType': reqType, 'userData': userData}), 200
        elif reqType == 'bdate':
            date = dt.datetime.strptime(userData, '%Y-%m-%d')
            weekday = date.strftime('%a')
            print(weekday)
            cur.execute(
                'update user_info set birth_date=%s, birth_day=%s where user_id=%s', (userData, weekday, userID))
            con.commit()
            con.disconnect()
            return jsonify({'userID': userID, 'reqType': reqType, 'userData': userData})
        elif reqType == 'btime':
            cur.execute(
                'update user_info set birth_time=%s where user_id=%s', (userData, userID))
            con.commit()
            con.disconnect()
            return jsonify({'userID': userID, 'reqType': reqType, 'userData': userData})
        elif reqType == 'gender':
            cur.execute(
                'update user_info set gender=%s where user_id=%s', (userData, userID))
            con.commit()
            con.disconnect()
            return jsonify({'userID': userID, 'reqType': reqType, 'userData': userData})
        elif reqType == 'email':
            cur.execute(
                'update user_account set email=%s where id=%s', (userData, userID))
            con.commit()
            con.disconnect()
            return jsonify({'userID': userID, 'reqType': reqType, 'userData': userData})
        elif reqType == 'phone':
            cur.execute(
                'update user_account set phone=%s where id=%s', (userData, userID))
            con.commit()
            con.disconnect()
            return jsonify({'userID': userID, 'reqType': reqType, 'userData': userData})
    return jsonify({"message": 'forbidden access', 'status': 'failed'}), 403


@user_webview_profile.route('/change-password', methods=['POST'])
def changePassword():
    header = request.headers
    authKey = header.get('Authorization')
    serverAuth = '88d464b2c2f13bcd7d1d648126e0e8aa5abeb5b1a209639f4e53d994696a422587b403fd69e1baa27b21deb03c2020fd3303e5cdc3ded8e0bc686b5dbbcd37ae'
    if authKey == serverAuth:
        accType = request.form['accType']
        if accType == 'email':
            userID = request.form['userID']
            oldPass = request.form['oldPass']
            newPass = request.form['newPass']
            con = db_connect()
            cur = con.cursor(dictionary=True, buffered=True)
            cur.execute(
                'select password from user_account where id=%s', (userID,))
            curPass = cur.fetchone()['password']
            if pbkdf2_sha256.verify(oldPass, curPass):
                if newPass != oldPass:
                    cur.execute(
                        'update user_account set password=%s where id=%s', (pbkdf2_sha256.hash(newPass), userID))
                    con.commit()
                    con.disconnect()
                    return jsonify({"message": 'Password is successfully updated', 'status': 'success'}), 200
                return jsonify({"message": 'New password cannot be the same as current password', 'status': 'failed'}), 422
            return jsonify({"message": 'Invalid password', 'status': 'failed'}), 401
    return jsonify({"message": 'forbidden access', 'status': 'failed'}), 403

# *************************************************************************************************************************************************
