#!/usr/bin/env python3
#coding: utf-8
from flask import Flask, render_template, Markup, request, redirect, url_for, make_response
from classes import task
from datetime import datetime, timedelta
from funcs import *
from random import choice

#!---------- sq_todo.py ----------
# My todo list
#-----------------------------!


#----------! MAIN
app = Flask(__name__)
mktaskdir()


#Homepage, GET : getting the page. Maybe getting it with arguments generated by a button on the page, in which case we take it into account
@app.route('/', methods=['GET'])
def render():
    #Does the user have a theme ?
    #theme list
    themes = getthemes()

    #Setting default theme if the user does not have one...
    if request.cookies.get('csslink') is None:
        csslink = themes[0]
        resp = make_response(redirect(request.path,code=302))
        resp.set_cookie("csslink", csslink)
        return resp
    #...or using their preferred theme if do have one
    else:
        csslink = request.cookies.get('csslink')
        resp = make_response(render_template("homepage.html", ntodo = todotasks(gettasks()), npers = personnaltasks(gettasks()),  ndone = donetasks(gettasks()), csslink = csslink))

    #Delete has been clicked
    if request.args.get("delete") is not None:
        todelete = request.args.get("delete")
        deltask(int(todelete))
        resp = make_response(render_template("homepage.html", ntodo = todotasks(gettasks()), npers = personnaltasks(gettasks()),  ndone = donetasks(gettasks()), csslink = csslink))

    #Edit has been clicked
    elif request.args.get("edit") is not None:
        toedit = request.args.get("edit")
        return redirect(url_for('edit', tasknumber=toedit))

    #Switch theme has been clicked
    elif request.args.get("switchpls") is not None:
        switchpls = request.args.get("switchpls")
        #Clicking "Change theme" switches to a random (other) theme
        current = csslink
        while csslink == current:
            csslink = choice(themes)

        #Commiting new theme, setting cookie for it, return template
        resp = make_response(redirect(request.path,code=302))
        resp.set_cookie('csslink', csslink)
        return resp

    #Read has been clicked
    elif request.args.get("toread") is not None:
        toread = request.args.get("toread")
        return redirect(url_for('readmode', task=(int(toread))))

    #Task is done or todo (switched)
    elif request.args.get("toswitch") is not None:
        toswitch = request.args.get("toswitch")
        mytask = findtask(int(toswitch))
        print(mytask)
        mytask = switchstatus(mytask)
        deltask(toswitch)
        addtask(mytask)
        resp = make_response(render_template("homepage.html", ntodo = todotasks(gettasks()), npers = personnaltasks(gettasks()),  ndone = donetasks(gettasks()), csslink = csslink))
    else:
        resp = make_response(render_template("homepage.html", ntodo = todotasks(gettasks()), npers = personnaltasks(gettasks()),  ndone = donetasks(gettasks()), csslink = csslink))

    return resp

#Homepage, POST : a task has been written and posted
@app.route('/', methods=['POST'])
def homepage():
    import time

    #theme
    csslink = request.cookies.get('csslink')

    #New task
    try:
        tasktitle = request.form['title']
        tasktext = request.form['text']
        priority = request.form['priority']

        if "personnal" in request.form.keys():
            personnal = True
        else:
            personnal = False

        print(f"Got new task with prio {priority}")

        rightnow = int(time.time())
        newtask = task(createtime=rightnow, modtime=rightnow, title=tasktitle, text=tasktext, done=False, priority=int(priority), personnal=False)
        addtask(newtask)
    except Exception as E:
        print(f"!!!!!!!!!! {E} - {request.form}")
        pass
    return render_template("homepage.html", ntodo = todotasks(gettasks()), npers = personnaltasks(gettasks()),  ndone = donetasks(gettasks()), csslink = csslink)


#Export mode
@app.route('/export', methods=['GET'])
def rawtasks():
    #No theme in export
    return render_template("export.html", rawtasks = exporttasks())

#Edition mode
@app.route('/edit', methods=['GET', 'POST'])
def edit():
    import time
    #theme
    csslink = request.cookies.get('csslink') 

    #Render edition page (Landing)
    if request.method == "GET":
        tasknumber = request.args.get("tasknumber")
        mytask = findtask(int(tasknumber))
        #Is task done ? 
        if mytask.donemark == "✅":
            todoselected = ""
            doneselected = "selected"
        else:
            todoselected = "selected"
            doneselected = ""

        #Is it personnal ?
        if mytask.personnal:
            pers_checked = "checked"
        else: 
            pers_checked = ""

        return render_template("edit.html", tasknumber=tasknumber, ntitle=mytask.title, ntext=mytask.text, csslink = csslink, priority=mytask.priority, taskdonemark=mytask.donemark, todoselected=todoselected, doneselected=doneselected, pers_checked=pers_checked)

    #Handling post
    if request.method == "POST":
        #Load values
        tasktitle = request.form['title']
        tasktext = request.form['text']
        tasknumber = int(request.form['tasknumber'])
        taskpriority = int(request.form['priority'])
        #Treat the "done" value which is annoying
        doneselected = request.form['donemark']
        if doneselected == "✅":
            taskdone = True
        else:
            taskdone = False
        if "personnal" in request.form.keys():
            personnal = True
        else:
            personnal = False
        deltask(tasknumber)
        rightnow = int(time.time())
        newtask = task(createtime=tasknumber, modtime=rightnow, title=tasktitle, text=tasktext, done=taskdone, priority=taskpriority, personnal = personnal)
        addtask(newtask)
        return render_template("homepage.html", ntodo = todotasks(gettasks()), npers = personnaltasks(gettasks()),  ndone = donetasks(gettasks()), csslink = csslink)



if __name__ == '__main__':
    convertemoji()
    app.run(host="0.0.0.0")
