#
# See LICENCE for detail
# Copyright (c) 2014 IRI
#

import json

from flask import render_template, jsonify, request, abort
from jinja2 import Markup
from sqlalchemy.orm import joinedload

from webapp import app
from database import db_session
import models

@app.route('/')
def page_home():
    events = db_session.query(models.Event).filter(models.Event.active == True).order_by(models.Event.start_date, models.Event.code).all()
    return render_template('index.html', events=events)


@app.route('/annot')
def page_annot():
    return render_template('annot.html')


@app.route('/annotationclient')
def page_annotationclient():
    return render_template('annotationclient.html', logging=True)

@app.route('/annotationclient/<event_code>')
def page_annotationclient_event_code(event_code):
    event_query = db_session.query(models.Event).filter(models.Event.code == event_code, models.Event.active == True)
    event = event_query.first()

    if not event:
        abort(404)

    #TODO: See why the relationship management does not work
    event_session_q = db_session.query(models.EventSession).filter(models.EventSession.event_id==event.id).order_by(models.EventSession.order.desc())
    event_session = event_session_q.first()

    categories_json = None

    if event_session:
        categories_json = event_session.categories_json

    if not categories_json:
        categories_json = None

    return render_template('annotationclient.html',
        logging = True,
        event_code = event_code,
        categories_json = Markup(json.dumps(categories_json).replace('\'','\\\'')) if categories_json else None
    )


@app.route('/pianoroll')
def page_pianoroll():
    events = db_session.query(models.Event).filter(models.Event.active == True).order_by(models.Event.start_date, models.Event.code).all()
    return render_template('pianoroll_index.html', events=events)

@app.route('/pianoroll/pr/<event_code>')
def page_pianoroll_event_code(event_code):
    event = db_session.query(models.Event).filter(models.Event.code == event_code, models.Event.active == True).first()
    if not event:
        abort(404)

    return render_template('pianoroll.html', logging=True, event=event)

@app.route('/pianoroll/av/<event_code>')
def page_annotviz_event_code(event_code):
    event = db_session.query(models.Event).filter(models.Event.code == event_code, models.Event.active == True).first()
    if not event:
        abort(404)

    return render_template('annotviz.html', logging=True, event=event)



@app.route('/api/test', methods=['PUT', 'POST'])
def new():
    return jsonify(request.get_json(force=False))
