def edit_qte(id):
    if request.json['action'] == 'put':
        qte = models.fromJso(request.json['qte'], models.Qte)
        # verify no overlapping qtes
        #  t----f t-f t----f
        #     t---------f
        # yes this is row-by-agonizing-row but there should only be one row
        # right now the debug info is more useful than optimizing with a bulk delete
        to_delete = g.db.query(models.Qte).filter(models.Qte.disc_id == id,
            models.Qte.ms_trigger <= qte.ms_finish, models.Qte.ms_finish >= qte.ms_trigger)
        print "adding qte", qte.ms_trigger, qte.ms_finish
        for qte_to_delete in to_delete:
            print "  deleting", qte_to_delete.ms_trigger, qte_to_delete.ms_finish
            g.db.delete(qte_to_delete)
        qte.disc_id = id
        g.db.add(qte)
        g.db.commit()
        return flask.jsonify(err='ok', csrf=g.session.guid)
    elif request.json['action'] == 'delete':
        deleted = g.db.query(models.Qte).filter_by(disc_id=id, ms_trigger=request.json['ms_trigger']).delete()
        if deleted > 0:
            print "DELETE: ", deleted, "qtes deleted", request.json['ms_trigger']
        else:
            print "DELETE: nothing deleted", request.json['ms_trigger']
        g.db.commit()
        return flask.jsonify(err='ok', csrf=g.session.guid)
    else:
        return flask.jsonify(err='invalid_action', csrf=g.session.guid)
def add_disc():
    # if not session.get('logged_in'):
    #     abort(401)
    disc = models.fromJso(request.form, models.Disc, ('title', 'url', 'ktube'))
    g.db.add(disc)
    g.db.commit()
    flask.flash("New entry was successfully posted")
    return flask.redirect(flask.url_for('list_discs'))
def disc_edit(id):
    if request.method == 'POST':
        try:
            jsoDisc = json.loads(request.form['jsonNew'])
            if 'qtes' in jsoDisc:
                g.db.query(models.Qte).filter(models.Qte.disc_id == id).delete()
                for jsoQte in jsoDisc['qtes']:
                    qte = models.fromJso(jsoQte, models.Qte)
                    qte.disc_id = id
                    g.db.add(qte)
                g.db.commit()
            else:
                raise Exception("Invalid json")
        except:
            g.db.rollback()
            flask.flash("Could not parse json")
    return render_disc(id, urlPostQte=flask.url_for('edit_qte', id=id, _external=True), csrf=create_session(id).guid)