import random
import time
import toml
from lang import Lang
from menu import Menu
from os import listdir
from os.path import isfile, join
from pyfiglet import Figlet


def find_langs():
    langs = ["lang/" + f for f in listdir("lang") if f[-5:] == ".stmp"]
    langs_o = []
    for lang in langs:
        with open(lang, encoding='utf-8') as lang_file:
            data = toml.load(lang_file)
            langs_o.append(Lang(data))
    return langs_o


def get_lang(id, langs):
    lang = [x for x in langs if x.id == id]
    if len(lang) == 0:
        return None
    else:
        return lang[0]


def get_level(num, lang):
    level = [x for x in lang.levels if x.num == num]
    if len(level) == 0:
        return None
    else:
        return level[0]


def select_char(chars):
    return random.choice(chars)


def question(chars):
    n = 10
    cor = 0
    while n != 0:
        char = select_char(chars)
        print(f"\n{char[0]}")
        ans = input("?").lower().strip()
        if ans == char[1]:
            print("Correct")
            cor += 1
        else:
            print("Wrong")
        n -= 1
    p_cor = (cor / 10) * 100
    print(f"{p_cor}% correct")


def run_levels(lang, levels):
    chars = []
    for level in levels:
        levels_o = (get_level(level, lang))
        for char in levels_o.chars:
            chars.append(char)
    question(chars)    


def run_lang(lang):
    levels = []
    print("\n---------------")
    print(f"Enter the number of the level you want to practice and press enter.\nMultiple levels can be selected. Enter a a number again to deselect the level.\nEnter [s] to start.")
    menu = Menu("")
    for level in lang.levels:
        char_s = ""
        for char in level.chars:
            char_s += f"{char[0]}, "
        menu.add(str(level.num), f"{level.name} ({char_s[:-2]})")
    menu.add("s", "Start")
    menu.add("b", "Back")
    while True:
        id = menu.prompt()
        if id == "s":
            if len(levels) == 0:
                print("Please select at least one level")
            else:
                run_levels(lang, levels)
        elif id == "b":
            pass
        else:
            if int(id) in levels:
                levels.remove(int(id))
            else:
                levels.append(int(id))


def start():
    langs = find_langs()
    if len(langs) == 0:
        print("No languages present in lang directory!")
        exit()
    menu = Menu("Choose a language")
    for lang in langs:
        menu.add(lang.id, lang.name)
    menu.add("b", "Back")
    id = menu.prompt()
    if id == "b":
        return
    else:
        run_lang(get_lang(id, langs))


def main_menu():
    while True:
        menu = Menu("Main menu")
        menu.add("b", "Begin", start)
        menu.add("s", "Settings", exit)
        menu.add("q", "Quit", exit)
        menu.prompt()


def main():
    splash()
    main_menu()
    


def splash():
    fig = Figlet(font="lean")
    print(fig.renderText("STMP")[:-100])
    print("By Ĉarli, Dinklederp, Flevosap\n")


if __name__=="__main__":
    main()
