##############################################################################
# ScoDoc
# Copyright (c) 1999 - 2023 Emmanuel Viennet.  All rights reserved.
# See LICENSE
##############################################################################

"""
  API : billets d'absences
"""

from flask import g, jsonify, request
from flask_login import login_required

import app
from app import db
from app.api import api_bp as bp, api_web_bp
from app.decorators import scodoc, permission_required
from app.scodoc.sco_utils import json_error
from app.models import BilletAbsence
from app.models.etudiants import Identite
from app.scodoc import sco_abs_billets
from app.scodoc.sco_permissions import Permission


@bp.route("/billets_absence/etudiant/<int:etudid>")
@api_web_bp.route("/billets_absence/etudiant/<int:etudid>")
@login_required
@scodoc
@permission_required(Permission.ScoView)
def billets_absence_etudiant(etudid: int):
    """Liste des billets d'absence pour cet étudiant"""
    billets = sco_abs_billets.query_billets_etud(etudid)
    return jsonify([billet.to_dict() for billet in billets])


@bp.route("/billets_absence/create", methods=["POST"])
@api_web_bp.route("/billets_absence/create", methods=["POST"])
@login_required
@scodoc
@permission_required(Permission.ScoAbsAddBillet)
def billets_absence_create():
    """Ajout d'un billet d'absence"""
    data = request.get_json(force=True)  # may raise 400 Bad Request
    etudid = data.get("etudid")
    abs_begin = data.get("abs_begin")
    abs_end = data.get("abs_end")
    description = data.get("description", "")
    justified = data.get("justified", False)
    if None in (etudid, abs_begin, abs_end):
        return json_error(
            404, message="Paramètre manquant: etudid, abs_bein, abs_end requis"
        )
    query = Identite.query.filter_by(etudid=etudid)
    if g.scodoc_dept:
        query = query.filter_by(dept_id=g.scodoc_dept_id)
    etud = query.first_or_404()
    billet = BilletAbsence(
        etudid=etud.id,
        abs_begin=abs_begin,
        abs_end=abs_end,
        description=description,
        etat=False,
        justified=justified,
    )
    db.session.add(billet)
    db.session.commit()
    return jsonify(billet.to_dict())


@bp.route("/billets_absence/<int:billet_id>/delete", methods=["POST"])
@api_web_bp.route("/billets_absence/<int:billet_id>/delete", methods=["POST"])
@login_required
@scodoc
@permission_required(Permission.ScoAbsAddBillet)
def billets_absence_delete(billet_id: int):
    """Suppression d'un billet d'absence"""
    query = BilletAbsence.query.filter_by(id=billet_id)
    if g.scodoc_dept is not None:
        # jointure avec departement de l'étudiant
        query = query.join(BilletAbsence.etudiant).filter_by(dept_id=g.scodoc_dept_id)
    billet = query.first_or_404()
    db.session.delete(billet)
    db.session.commit()
    return jsonify({"OK": True})
