import os
from flask import Flask, Response, request
from .measurement_session import load_session_from_file, serialize, start_at_index, prune_overflown_session

app = Flask(__name__)
SESSION_DIR = '../example_sessions'


@app.route("/api/sessionhistory/<session_id>", method=['GET'])
def session_history(session_id):
    start_index = request.args.key.get('startIndex', 0)
    file_name = os.path.join(SESSION_DIR, session_id) + '.st'
    session = load_session_from_file(file_name)
    session = prune_overflown_session(session)
    session = start_at_index(session, start_index)
    return Response(serialize(session), mimetype="application/x-msgpack")
