# Framework libraries
from flask import Flask, render_template, request
from sqlalchemy import exc

# Local libraries
from database import DeveloperInfo, db_session, init_db
from spreadsheet import load_roster

# Python libraries
import argparse
import json


app = Flask(__name__)


def error(msg, code=400):
    data = json.dumps({'msg': msg, 'error': code})
    return data, code


@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()


@app.route("/", methods=['GET'])
def index():
    return render_template('attendance.html')


@app.route("/teams", methods=['GET'])
def teams_list():
    teams = ['Arena', 'Server/Client', 'Testing', 'Visualizer', 'Web']
    return json.dumps(teams)


@app.route("/devs", methods=['GET', 'POST'])
def dev_list():
    if request.method == 'GET':
        return json.dumps([x.to_dict() for x in DeveloperInfo.all()])

    # It must be a POST
    try:
        return DeveloperInfo.from_dict(request.form).to_json()
    except exc.IntegrityError, e:
        return error(e.message)


@app.route("/devs/<dev_id>", methods=['GET', 'PUT'])
def dev_detail(dev_id):
    dev = DeveloperInfo.get(dev_id)
    if not dev:
        return json.dumps(None)

    if request.method == 'GET':
        return dev.to_json()

    # It must be a PUT
    dev.update(request.get_json())
    try:
        db_session.commit()
        return dev.to_json()
    except exc.IntegrityError, e:
        return error(e.message)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("roster",
                        nargs='?',
                        type=file,
                        help="Tab-separated spreadsheet of people")
    args = parser.parse_args()

    init_db()

    if args.roster:
        print "Populating database using spreadsheet..."
        load_roster(db_session, args.roster)
        print "\tDone"

    app.run(debug=True)

@@ -131,16 +131,28 @@
 e import
+ Attendance,
  Develop
@@ -1339,16 +1339,34 @@
 t_json()
+ or request.values
 )%0A    tr
@@ -1493,16 +1493,632 @@
 sage)%0A%0A%0A
+@app.route(%22/attendance/%3Cdev_id%3E%22, methods=%5B'GET', 'POST'%5D)%0Adef attendance_detail(dev_id):%0A    dev = DeveloperInfo.get(dev_id)%0A    latest = Attendance.latest_for(dev)%0A    if not dev:%0A        return json.dumps(None)%0A%0A    if request.method == 'GET':%0A        return latest.to_json() if latest else json.dumps(None)%0A%0A    # It must be a POST%0A    here = (request.get_json() or request.values).get('here', True)%0A    latest = Attendance(dev=dev.id, here=here)%0A    db_session.add(latest)%0A    try:%0A        db_session.commit()%0A        return latest.to_json()%0A    except exc.IntegrityError, e:%0A        return error(e.message)%0A%0A%0A
 if __nam

Add an attendance endpoint