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

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 datetime import datetime as dt, timedelta
import datetime as dt2
from htmlmin.minify import html_minify


admin_upload_hawsartan_result = Blueprint("admin_upload_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_upload_hawsartan_result.route('/weekly', methods=['GET'])
@sessionAuth
def weeklyHawSarTan():
    con = db_connect()
    cur = con.cursor(dictionary=True)
    cur.execute(
        'select distinct(start_date), end_date from script_week')
    mScriptData = cur.fetchall()
    # print(mScriptData)
    return html_minify(render_template('admin_upload_hawsartan_result.html', title='အပတ်စဥ် ဟောစာတမ်း data ထည့်ရန်', stype=0, scriptData=mScriptData))


@admin_upload_hawsartan_result.route('/monthly', methods=['GET'])
@sessionAuth
def monthlyHawSarTan():
    con = db_connect()
    cur = con.cursor()
    cur.execute(
        'select id,start_date,end_date,script_eng,script_mm from script_month')
    mScriptData = cur.fetchall()
    return html_minify(render_template('admin_upload_hawsartan_result.html', title='လစဥ် ဟောစာတမ်း data ထည့်ရန်', stype=1, scriptData=mScriptData))


@admin_upload_hawsartan_result.route('/yearly', methods=['GET'])
@sessionAuth
def yearlyHawSarTan():
    con = db_connect()
    cur = con.cursor()
    cur.execute(
        'select id,start_date,end_date,script_eng,script_mm from script_year')
    mScriptData = cur.fetchall()
    return html_minify(render_template('admin_upload_hawsartan_result.html', title='နှစ်စဥ် ဟောစာတမ်း data ထည့်ရန်', stype=2, scriptData=mScriptData))


@admin_upload_hawsartan_result.route('/upload-hawsartan-data', methods=['POST'])
@sessionAuth
def uploadHawSarTan():
    if request.method == 'POST':
        con = db_connect()
        cur = con.cursor()
        stype = int(request.form['stype'])

        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 = []
        dayCount = 0

        while dayCount < 7:
            result_mm = request.form['result_mm_'+str(dayCount)]
            result_eng = request.form['result_eng_'+str(dayCount)]
            dataItem = (start_date, end_date, result_eng,
                        result_mm, datetime, dayCount)
            dataList.append(dataItem)
            dayCount += 1
        if stype == 0:
            cur.executemany('insert into script_week (start_date,end_date,script_eng,script_mm,datetime,day_id) values (%s,%s,%s,%s,%s,%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('insert into script_month (start_date,end_date,script_eng,script_mm,datetime) values (%s,%s,%s,%s,%s)',
        #                 (start_date, end_date, result_eng, result_mm, datetime))
        #     con.commit()
        #     con.disconnect()
        #     flash('data successfully added.', 'success')
        #     return redirect(url_for('admin_upload_hawsartan_result.monthlyHawSarTan'))
        # if stype == 2:
        #     cur.execute('insert into script_year (start_date,end_date,script_eng,script_mm,datetime) values (%s,%s,%s,%s,%s)',
        #                 (start_date, end_date, result_eng, result_mm, datetime))
        #     con.commit()
        #     con.disconnect()

        #     flash('data successfully added.', 'success')
        #     return redirect(url_for('admin_upload_hawsartan_result.yearlyHawSarTan'))


@admin_upload_hawsartan_result.route('/delete-hawsartan-data', methods=['GET'])
@sessionAuth
def deleteHawSarTan():
    if 'innerSession' in session and request.method == 'GET':
        con = db_connect()
        cur = con.cursor()
        stype = int(request.args.get('stype'))
        hid = request.args.get('hid')
        if stype == 0:
            cur.execute('delete from script_week where id=%s', (hid,))
            con.commit()
            con.disconnect()
            flash('data successfully deleted.', 'warning')
            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('delete from script_month where id=%s', (hid,))
        #     con.commit()
        #     con.disconnect()
        #     flash('data successfully deleted.', 'warning')
        #     return redirect(url_for('admin_upload_hawsartan_result.monthlyHawSarTan'))
        # elif stype == 2:
        #     cur.execute('delete from script_year where id=%s', (hid,))
        #     con.commit()
        #     con.disconnect()
        #     flash('data successfully deleted.', 'warning')
        #     return redirect(url_for('admin_upload_hawsartan_result.yearlyHawSarTan'))


@admin_upload_hawsartan_result.route('/weekly/upload', methods=['GET'])
@sessionAuth
def uploadWeekly():
    stype = int(request.args.get('stype'))
    title = ''
    today = dt2.date.today()
    start_of_week = today - dt2.timedelta(days=today.weekday() + 1)
    print(start_of_week)
    if stype == 0:
        title = 'Add Weekly Data'
    # elif stype == 1:
    #     title = 'Add Monthly Data'
    # elif stype == 2:
    #     title = 'Add Yearly Data'
    return html_minify(render_template('admin_upload_hawsartan_insert.html', title=title, stype=stype,
                                       startDays=sunday_dates_in_current_month(), start_of_week=start_of_week))
