import os
import flask
from font_game.images import purge_images
from font_game.game import start_game, purge_games, guess_font, test_game
from font_game import FONTS, read_file

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 test_game(game_id):
            return flask.redirect("/")

        guess_font(game_id, font_guess)

    args = flask.request.args
    if 'id' in args:
        game_id = args['id']
        if not test_game(game_id):
            return flask.redirect("/")

        game = read_file(f"current_games/{game_id}")

        if int(game['i']) == int(game['game_length']):
            os.remove(f"current_games/{game_id}")
            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)

@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 = int(flask.request.form['game_length'])
    else:
        game_length = 10

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

@app.route("/all")
def all_fonts():
    pass
