import datetime

from apiflask import APIBlueprint
from flask import abort

from ..schemas import MessageSchema, TemporaryStudentSchema, ExaminationScheduleListSchema, \
    TermOfDefenceStudentListSchema
from ...dependencies import db
from ..models import Student, Group, TermOfDefence
from ...examination_schedule.models import ExaminationSchedule
from ...project_supervisor.models import ProjectSupervisor

bp = APIBlueprint("enrollments", __name__, url_prefix="/")


@bp.post('/<int:examination_schedule_id>/enrollments/<int:term_of_defence_id>/')
@bp.input(TemporaryStudentSchema)
@bp.output(MessageSchema)
def assign_your_group_to_term_of_defence(examination_schedule_id: int, term_of_defence_id: int, data: dict) -> dict:
    # this code will be removed
    student = Student.query.filter(Student.index == data['student_index']).first()
    if student is None:
        abort(404, "Student doesn't exist!")
    ################
    term_of_defence = TermOfDefence.query.filter(TermOfDefence.id == term_of_defence_id,
                                                 TermOfDefence.examination_schedule_id == examination_schedule_id).first()
    ex = term_of_defence.examination_schedule
    if term_of_defence is None or ex is None:
        abort(400, "Term of defence not found!")

    g = Group.query.join(ProjectSupervisor).filter(Group.year_group_id == ex.year_group_id). \
        join(Group.students).filter_by(index=student.index).first()
    if g is None or g.project_supervisor is None:
        abort(400, "You don't have a group or your group doesn't have an assigned project supervisor!")

    defence = TermOfDefence.query.filter(TermOfDefence.group_id == g.id,
                                         TermOfDefence.examination_schedule_id == examination_schedule_id).first()
    if defence is not None:
        abort(400, "Your group has already assigned to any exam date!")

    td = TermOfDefence.query.join(TermOfDefence.members_of_committee). \
        filter_by(id=g.project_supervisor_id).first()

    if td is None:
        abort(400, "Your project supervisor is not in committee!")

    term_of_defence.group_id = g.id
    db.session.add(term_of_defence)
    db.session.commit()
    return {"message": "You have just assigned the group for this exam date!"}


@bp.delete('/<int:examination_schedule_id>/enrollments/<int:term_of_defence_id>/')
@bp.input(TemporaryStudentSchema)
@bp.output(MessageSchema)
def delete_your_group_from_term_of_defence(examination_schedule_id: int, term_of_defence_id: int, data: dict) -> dict:
    # this code will be removed
    student = Student.query.filter(Student.index == data['student_index']).first()
    if student is None:
        abort(404, "Student doesn't exist!")
    ################

    term_of_defence = TermOfDefence.query.join(ExaminationSchedule).filter(TermOfDefence.id == term_of_defence_id). \
        filter(TermOfDefence.examination_schedule_id == examination_schedule_id).first()

    ex = term_of_defence.examination_schedule
    if term_of_defence is None:
        abort(404, "Term of defence doesn't exist!")

    group = Group.query.filter(Group.year_group_id == ex.year_group_id). \
        join(Group.students).filter_by(index=student.index).first()
    if group.id != term_of_defence.group_id:
        abort(400, "You are not assigned to this group!")

    term_of_defence.group_id = None
    db.session.add(term_of_defence)
    db.session.commit()

    return {"message": "You have just removed the group for this exam date!"}


@bp.get('/examination-schedule/year-group/<int:year_group_id>/')
@bp.input(TemporaryStudentSchema, location='query')
@bp.output(ExaminationScheduleListSchema)
def list_examination_schedule(year_group_id: int, data: dict) -> dict:
    # this code will be removed
    student = Student.query.filter(Student.index == data['student_index']).first()
    if student is None:
        abort(404, "Student doesn't exist!")
    ################

    # in the future filter after the mode of examination schedule if we will have authorization module
    now = datetime.datetime.utcnow()
    examination_schedules = ExaminationSchedule.query. \
        filter(ExaminationSchedule.year_group_id == year_group_id). \
        filter(ExaminationSchedule.start_date_for_enrollment_students < now). \
        filter(ExaminationSchedule.end_date_for_enrollment_students > now).all()
    return {'examination_schedules': examination_schedules}


@bp.get('/examination-schedule/<int:examination_schedule_id>/enrollments/')
@bp.input(TemporaryStudentSchema, location='query')
@bp.output(TermOfDefenceStudentListSchema)
def list_term_of_defences(examination_schedule_id: int, data: dict) -> dict:
    # this code will be removed
    student = Student.query.filter(Student.index == data['student_index']).first()
    if student is None:
        abort(404, "Student doesn't exist!")
    ################
    # in the future filter after the mode of examination schedule if we will have authorization module
    now = datetime.datetime.utcnow()
    term_of_defences = TermOfDefence.query.filter(TermOfDefence.examination_schedule_id == examination_schedule_id). \
        join(ExaminationSchedule, isouter=True). \
        filter(ExaminationSchedule.start_date_for_enrollment_students < now). \
        filter(ExaminationSchedule.end_date_for_enrollment_students > now).all()

    return {'term_of_defences': term_of_defences}