from flask import render_template
from flask import request
from flask import Response

from Utils import isInt

from View.WebGUI import app
from View.WebGUI.FlaskRunner import FlaskRunner


@app.route('/students')
def students():
    sortMethod = request.args.get("sort")
    _students = []
    for student in FlaskRunner.catalogController.getStudents():
        average = FlaskRunner.catalogController.getAverageByStudentID(student.getId())
        _students.append({
            'name': student.getName(),
            'id': student.getId(),
            'average': average,
            'failing': True if average < 5 else False
        })
    if sortMethod:
        if sortMethod == '0':
            _students = sorted(_students, key=lambda x: x['name'])
        else:
            _students = sorted(_students, key=lambda x: x['average'], reverse=True)
    else:
        _students = sorted(_students, key=lambda x: x['name'])

    return render_template("students.html", students=_students)


@app.route('/student/<studentId>')
def student(studentId):
    if not isInt(studentId):
        return Response(response='{ status: "Invalid student id }',
                        status=422,
                        mimetype="application/json")
    studentId = int(studentId)

    _student = FlaskRunner.catalogController.getStudentById(studentId)
    if not _student:
        return Response(response='{ status: "Invalid student id }',
                        status=404,
                        mimetype="application/json")

    _disciplines = []
    for discipline in FlaskRunner.catalogController.getDisciplinesByStudentId(studentId):
        _disciplines.append({
            'name': discipline.getName(),
            'id': discipline.getId(),
            'average': FlaskRunner.catalogController.getAverageAtDisciplineByStudentID(studentId, discipline.getId()),
            'grades': [grade.getGrade() for grade in
                       FlaskRunner.catalogController.getGradesByStudentIdAndDisciplineId(studentId,
                                                                                         discipline.getId())]
        })

    return render_template("student.html", student={'name': _student.getName(),
                                                    'id': _student.getId()
                                                    }, disciplines=_disciplines)