#!/usr/bin/env python3
#coding: utf-8
from classes import task

def mktaskdir():
    """
    Create our data directory if does not exist.
    """
    from os.path import exists
    from os import mkdir

    if not exists("./data"):
        mkdir("./data")

def dumptasks(tasks):
    """
    Get our tasks list and save them as pickle to tasks.pickle
    """
    import pickle
    with open('./data/tasks.pickle', 'wb') as mpf:
        pickle.dump(tasks, mpf)

    return True

def gettasks():
    """
    Get our tasks from the file tasks.pickle
    """
    from os.path import exists
    import pickle

    if exists("./data/tasks.pickle"):
        with open('./data/tasks.pickle', 'rb') as mpf:
            tasks = pickle.load(mpf)
    else:
        tasks = []

    return tasks

def cattasks(tasklist: list):
    """
    Concatenate a list of tasks into a str.
    """
    final = ""
    for task in tasklist:
        final += task.flaskrender()

    return final

def deltask(timestamp: int):
    """
    Delete task in our pickle file for which the createtime corresponds to timestamp
    """
    tasks = gettasks()
    for task in tasks:
        if int(task.createtime) == int(timestamp):
            tasks.remove(task)
            dumptasks(tasks)
            return True
    return False

def findtask(createtime: int):
    """
    Find a task in our pickle file of tasks by its createtime
    """
    tasks = gettasks()
    for task in tasks:
        if task.createtime == createtime:
            return task

def addtask(mytask: task):
    """
    Add a task to our tasks pickle file (and sort it).
    """
    tasks = gettasks()
    tasks.append(mytask)
    tasks = sorted(tasks, key=lambda task: task.priority, reverse=True)
    dumptasks(tasks)

def exporttasks():
    """
    Export our tasks in markdown, one after the other.
    """
    tasks = gettasks()
    rawtext = ""
    for task in tasks:
        rawtext += f"#{task.title}\n"
        rawtext += f"* Created: {task.rendertime(task.createtime)}\n"
        rawtext += f"* Modified: {task.rendertime(task.modtime)}\n"
        rawtext += f"{task.text}\n"
        rawtext += f"-----\n\n"

    return rawtext

    return 

def getthemes():
    """
    Find all themes present in our css folder and return a nice list of
    css links, for the user to pick into
    """
    from flask import url_for
    from os import listdir

    allfiles = listdir("./static/styles")
    themefiles, themes = [], []
    for myfile in allfiles:
        if myfile.endswith(".css"):
            themefiles.append(myfile)

    for themefile in themefiles:
        themes.append(url_for('static', filename=f'styles/{themefile}'))

    return themes

def switchstatus(task):
    """
    Switches the status of a task from todo to done, or vice-versa
    Also updates the modtime
    """
    import time

    rightnow = int(time.time())
    if task.donemark == "✅":
        task.donemark = "⚠️"
    else:
        task.donemark = "✅"

    task.modtime=rightnow

    return task

def todotasks(tasklist):
    """
    Sorts tasks in tasklist: Gives todotasks sorted by priority
    """
    buffer = []
    finalstr = ""
    for task in tasklist:
        if task.donemark == "⚠️":
            buffer.append(task)

    tasks = sorted(buffer, key=lambda task: task.priority, reverse=True)
    for task in tasks:
        finalstr += task.flaskrender()

    return finalstr

def personnaltasks(tasklist):
    """
    Sorts tasks in tasklist: Gives todotasks sorted by priority
    """
    buffer = []
    finalstr = ""
    for task in tasklist:
        if task.donemark == "🔒":
            buffer.append(task)

    tasks = sorted(buffer, key=lambda task: task.priority, reverse=True)
    for task in tasks:
        finalstr += task.flaskrender()

    return finalstr

def donetasks(tasklist):
    """
    Sorts tasks in tasklist: Gives done tasks sorted by modtime
    """
    buffer = []
    finalstr = ""
    for task in tasklist:
        if task.donemark == "✅":
            buffer.append(task)

    tasks = sorted(buffer, key=lambda task: task.modtime, reverse=True)
    for task in tasks:
        finalstr += task.flaskrender()

    return finalstr

def convertemoji():
    tasks = gettasks()
    for task in tasks:
        if task.donemark not in ["⚠️", "✅", "🔒"]:
            task.donemark = "⚠️"
    dumptasks(tasks)




