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

from datetime import datetime as dt, timedelta
from flask import render_template, request, session, redirect, url_for, flash, Blueprint
from modules.database_modules import db_connect
from functions.date_time_functions import sunday_dates_in_current_month, upload_time
from htmlmin.minify import html_minify


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


def sessionAuth(function):
    def wrapper(*args, **kwargs):
        if 'innerSession' in session:
            return function()
        else:
            return redirect(url_for('adminLogin'))

    wrapper.__name__ = function.__name__
    return wrapper


@admin_update_hawsartan_result.route('/')
def updateHawSarTan():
    date = request.args.get('date')
    stype = int(request.args.get('stype'))
    con = db_connect()
    cur = con.cursor(dictionary=True)
    # sdata = None
    if stype == 0:
        cur.execute(
            'select id, day_id, script_eng, script_mm from script_week where start_date=%s', (date,))
        rData1 = cur.fetchall()
        # print(rData1)
        cur.execute(
            'select distinct(start_date), end_date from script_week where start_date=%s', (date,))
        rData2 = cur.fetchone()
        # print(rData2)
    #! due to the workflow the following functions will be temporary disabled
    # elif stype == 1:
    #     cur.execute(
    #         'select start_date, end_date, script_eng, script_mm from script_month where id=%s', (date,))
    #     sdata = cur.fetchall()

    # elif stype == 2:
    #     cur.execute(
    #         'select start_date, end_date, script_eng, script_mm from script_year where id=%s', (date,))
    #     sdata = cur.fetchall()

    return html_minify(render_template('admin_update_hawsartan_result.html', rData2=rData2,
                                       rData1=rData1, stype=stype, hid=date, startDays=sunday_dates_in_current_month()))


@admin_update_hawsartan_result.route('/update', methods=['POST'])
@sessionAuth
def postUpdateHawSarTan():
    con = db_connect()
    cur = con.cursor()
    stype = int(request.form['stype'])
    # print(stype)

    dayCount = 0

    hid = request.form['hid']
    start_date = request.form['start_date']
    end_date = (dt.strptime(start_date, '%Y-%m-%d') +
                timedelta(days=6)).strftime('%Y-%m-%d')
    datetime = upload_time()
    dataList = []
    while dayCount < 7:
        result_mm = request.form['result_mm_'+str(dayCount)]
        result_eng = request.form['result_eng_'+str(dayCount)]
        special_id = request.form['special_id_'+str(dayCount)]
        dataItem = (start_date, end_date, result_eng,
                    result_mm, datetime, dayCount, special_id)
        dataList.append(dataItem)
        dayCount += 1
    if stype == 0:
        cur.executemany('update script_week set start_date=%s,end_date=%s,script_eng=%s,script_mm=%s,datetime=%s where day_id=%s and id=%s',
                        dataList)
        con.commit()
        con.disconnect()
        flash('data successfully added.', 'success')
        return redirect(url_for('admin_upload_hawsartan_result.weeklyHawSarTan'))
    #! due to the workflow the following functions will be temporary disabled
    # elif stype == 1:
    #     cur.execute('update script_month set start_date=%s,end_date=%s,script_eng=%s,script_mm=%s,datetime=%s where id=%s',
    #                 (start_date, end_date, result_eng, result_mm, datetime, hid))
    #     con.commit()
    #     con.disconnect()
    #     flash('data successfully added.', 'success')
    #     return redirect(url_for('admin_upload_hawsartan_result.monthlyHawSarTan'))
    # elif stype == 2:
    #     cur.execute('update script_month set start_date=%s,end_date=%s,script_eng=%s,script_mm=%s,datetime=%s where id=%s',
    #                 (start_date, end_date, result_eng, result_mm, datetime, hid))
    #     con.commit()
    #     con.disconnect()
    #     flash('data successfully added.', 'success')
    #     return redirect(url_for('admin_upload_hawsartan_result.yearlyHawSarTan'))
    flash('Something went wrong.', 'danger')
    return redirect(url_for('admin_update_hawsartan_result.updateHawSarTan', stype=stype, hid=hid))
