import pathlib
import flask
from font_game.images import purge_images
from font_game.game import start_game, purge_games
from font_game import FONTS

app = flask.Flask(
    __name__,
    static_folder="../static",
    template_folder="../templates"
)

@app.before_first_request
def activate():
    purge_images()
    purge_games()

@app.route("/fontgame", methods=["GET", "POST"])
def font_game():
    if flask.request.method == "POST":
        game_id = flask.request.form['id']
        font_guess = flask.request.form['font']

        if not pathlib.Path(f"current_games/{game_id}").is_file():
            return flask.redirect("/")

        with open(f"current_games/{game_id}", "r+", encoding="utf-8") as file:
            game_dict = dict(
                [tuple(line.split(":")) for line in file.read().split('\n')]
            )
            i = int(game_dict['i'])
            font = game_dict['fonts'].split(',')[i]
            if font_guess == font:
                game_dict['points'] = str(int(game_dict['points']) + 1)
            game_dict['i'] = str(i+1)
            game = "\n".join(
                [f"{key}:{value}" for key, value in game_dict.items()]
            )
            file.seek(0)
            file.write(game)

    args = flask.request.args
    if 'id' in args:
        if not pathlib.Path(f"current_games/{args['id']}").is_file():
            return flask.redirect("/")

        with open(f"current_games/{args['id']}", "r", encoding="utf-8") as file:
            game = dict(
                [tuple(line.split(":")) for line in file.read().split('\n')]
            )

        if int(game['i']) == int(game['game_length']):
            return flask.render_template("final.html", points=game['points'],
                                         game_length=game['game_length'])

        images = game['images'].split(",")
        image = images[int(game['i'])]

        url = f"/static/images/{image}.png"
        parameters = {
            "url": url,
            "i": str(int(game['i']) + 1),
            "round_n": game['i'],
            "game_length": game['game_length'],
            "points":game['points'],
            "fonts":FONTS,
            "id":args['id']
        }
        return flask.render_template("fontgame.html", **parameters)

    if 'n' in flask.request.args:
        game_length = int(flask.request.args['n'])
    else:
        game_length = 10

    game_id = start_game(game_length)
    return flask.redirect(f"/fontgame?id={game_id}")

@app.route("/")
def root():
    return flask.render_template("menu.html")

@app.route("/startgame", methods=["POST"])
def start():
    if 'game_length' in flask.request.form:
        game_length = flask.request.form['game_length']
    else:
        game_length = 10
    return flask.redirect(f"/fontgame?n={game_length}")
