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

import os
from flask import Flask, render_template, request, session, redirect, url_for, flash, Blueprint, jsonify
from modules.database_modules import db_connect
from functions.date_time_functions import upload_time
from PIL import Image
from werkzeug.utils import secure_filename


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

user_image_upload = Blueprint("user_image_upload", __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 #########################################################################################################################################
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'webp', 'gif'])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

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


@user_image_upload.route("/", methods=['POST'])
def profileImgUpload():
    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)
        image = request.files.getlist('files[]')
        userID = request.form['userID']

        for file in image:
            if file and allowed_file(file.filename):
                filename = secure_filename(
                    f'KZT_profile_{userID}.' + file.filename.split('.')[1])
                path = f'/images/profile/{filename}'
                cur.execute(
                    'update user_account set img_path=%s where id=%s', (path, userID))
                con.commit()
                # listDir = os.listdir('./user_management/static/')

                file.save('./user_management/static/' + path)
                file_size = os.stat('./user_management/static/' + path).st_size
                if file_size >= 500000:
                    image = Image.open('./user_management/static/'+path)
                    new_image = image.resize(
                        (round(image.size[0]/4,), round(image.size[1]/4,)))
                    new_image.save('./user_management/static/'+path)
        return jsonify({'message': 'successfully updated', 'status': 'success'}), 200
    return jsonify({'message': 'unauthorized access'}), 403
# *************************************************************************************************************************************************
