import os
import uuid

from flask import Flask
from flask import request
from pymongo import Connection

from konfig import Konfig
from game import create_game
from game import add_story_to_game

app = Flask(__name__)
konf = Konfig()
#konf.use_dict({'mongo_url': 'localhost'})

mongo_database = konf.mongo_url
connection = Connection(mongo_database)
db = connection['game']
players = db.players


def get_id():
    id = str(uuid.uuid4())
    if 'From' in request.form and 'To' in request.form:
        id = "%s_%s" % (request.form['From'], request.form['To'])
    elif 'Caller' in request.form and 'Caller' in request.form:
        id = "%s_%s" % (request.form['Caller'], request.form['Called'])
    return id


def play(game, input):
    #FIXME: we shoudn't need to do this each time.
    # Perhaps we create an sms and voice object at the start
    # and pass the approprate one to this function?
    game = add_story_to_game(game)

    player_id = get_id()
    player = players.find_one({'player_id': player_id})
    if player is None:
        new_player = {'player_id': player_id,
                      'state': game.state}
        players.insert(new_player)
        #FIXME: There has to be a way to get this from the .insert call
        player = players.find_one({'player_id': player_id})
    print "PLAYER: ", player
    game.set_state(player['state'])
    game.next(input)
    players.update(player, {'$set': {'state': game.state}})
    return game.response


@app.route("/")
def hello():
    return "Hello."


@app.route("/sms", methods=['POST'])
def sms():
    game = create_game(type='sms')
    return play(game, str(request.form['Body']))


@app.route("/voice", methods=['POST'])
def voice():
    game = create_game(type='voice')
    input = ' '
    if 'Digits' in request.form:
        input = str(request.form['Digits'])
    return play(game, input)

if __name__ == "__main__":
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    if port == 5000:
        app.debug = True
    app.run(host='0.0.0.0', port=port)

@@ -1512,16 +1512,833 @@
 llo.%22%0A%0A%0A
+@app.route(%22/stats/%3Cnumber%3E%22)%0Adef stats(number):%0A    states = %5B'total', 'intro', 'intro2', 'part1', 'part2', 'part3', 'end'%5D%0A    values = %5B%5D%0A    for state in states:%0A        if state is 'total':%0A            values.append(players.count())%0A        else:%0A            values.append(players.find(%7B'state': state%7D).count())%0A    height = values%5B0%5D%0A    img = '%3Cimg src=%22'%0A    img += %22//chart.googleapis.com/chart%22%0A    img += %22?chxl=0:%7C%25s%22 %25 ('%7C'.join(states))%0A    img += %22&chxr=0,1,%25s%7C1,0,%25s%22 %25 (height, height)%0A    img += %22&chxt=x,y%22%0A    img += %22&chbh=a,5,11%22%0A    img += %22&chs=300x150%22%0A    img += %22&cht=bvg%22%0A    img += %22&chco=4D89F9%22%0A    img += %22&chds=0,%25s%22 %25 (height)%0A    img += %22&chd=t:%25s%22 %25 ','.join(str(x) for x in values)%0A    img += %22&chtt=Progress%22%0A    img += '%22 /%3E'%0A    return %22%3Chtml%3E%3Cbody%3E%25s%3C/body%3E%3C/html%3E%22 %25 img%0A%0A%0A%0A
 @app.rou

add basic stats capability