"""A flask API for generating (and retrieving) player details!

Usage:
    api.py run [--no-debug] [--port=<p>] [--host=<h>]
    api.py (-h | --help)

Options:
    -h --help          Show this screen
    --no-debug         Don't add debug=True when running
    --port=<p>         The port to use [default: 5000]
    --host=<h>         The host (address to listen on) [default: 0.0.0.0]
"""
import logging
import random

import docopt
import flask

from random_cricket_profiles import countries, player_generator, players, prettyint

logging.basicConfig(level=logging.INFO)

app = flask.Flask(__name__)
app.config.from_object("random_cricket_profiles.settings.Config")


generator = None


def get_player_generator():
    global generator
    filename = app.config["DATA_FILENAME"]
    min_profile_length = app.config["MIN_PROFILE_LENGTH"]
    if generator is None:
        sample_players = players.load_players(filename)
        generator = player_generator.PlayerGenerator(sample_players, min_profile_length)
    return generator


@app.route("/p/<country_code>/<seed_string>")
def player(country_code, seed_string):
    seed = prettyint.decode(seed_string)

    pg = get_player_generator()
    player, _seed = pg.generate(country_code=country_code, seed=seed)

    response = {
        "country": country_code,
        "firstnames": player.firstnames,
        "surname": player.surname,
        "profile": player.profile
    }

    return flask.jsonify(response)


@app.route("/p/random")
def random_player():
    country = random.choice(countries.COUNTRIES)
    country_code = country.country_code

    seed = random.getrandbits(64)
    seed_string = prettyint.encode(seed)

    url = flask.url_for("player", country_code=country_code, seed_string=seed_string)
    return flask.redirect(url)


if __name__ == "__main__":
    args = docopt.docopt(__doc__)

    if args.get("run"):
        port = int(args["--port"])
        host = args["--host"]
        debug = not bool(args.get("--no-debug"))

        app.run(host=host, port=port, debug=debug)
