from flask import Flask, redirect, flash, render_template, session, g, request, get_flashed_messages
import werkzeug.exceptions
import time
from datetime import datetime
import json

import hra.config as config
import hra.web.html as html
import hra.db as db
from hra.web import app, NeedLoginError
import hra.web.jinja_mac as jinja_mac


def get_context():
    if g.user is None:
        raise NeedLoginError
    game_id = request.args.get('game') or 1
    team_id = request.args.get('team') or 0
    game = db.get_session().query(db.Game).filter_by(game_id=game_id).first()
    print(game_id, game, team_id)
    if game is None:
        raise werkzeug.exceptions.NotFound("No such game")
    return game, team_id

@app.route("/api/state", methods=['GET'])
def api_state():
    game, team_id =  get_context()
    state = game.current_state()
    return json.dumps({
        "round": state.round,
        "state": state.state,
        })