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

"""
  ScoDoc 9 API : accès aux moduleimpl
"""

from flask import g
from flask_json import as_json
from flask_login import login_required

from app.api import api_bp as bp, api_web_bp
from app.decorators import scodoc, permission_required
from app.models import (
    FormSemestre,
    ModuleImpl,
)
from app.scodoc.sco_permissions import Permission


@bp.route("/moduleimpl/<int:moduleimpl_id>")
@api_web_bp.route("/moduleimpl/<int:moduleimpl_id>")
@login_required
@scodoc
@permission_required(Permission.ScoView)
@as_json
def moduleimpl(moduleimpl_id: int):
    """
    Retourne un moduleimpl en fonction de son id

    moduleimpl_id : l'id d'un moduleimpl

    Exemple de résultat :
        {
          "id": 1,
          "formsemestre_id": 1,
          "module_id": 1,
          "responsable_id": 2,
          "moduleimpl_id": 1,
          "ens": [],
          "module": {
            "heures_tp": 0,
            "code_apogee": "",
            "titre": "Initiation aux réseaux informatiques",
            "coefficient": 1,
            "module_type": 2,
            "id": 1,
            "ects": null,
            "abbrev": "Init aux réseaux informatiques",
            "ue_id": 1,
            "code": "R101",
            "formation_id": 1,
            "heures_cours": 0,
            "matiere_id": 1,
            "heures_td": 0,
            "semestre_id": 1,
            "numero": 10,
            "module_id": 1
          }
        }
    """
    query = ModuleImpl.query.filter_by(id=moduleimpl_id)
    if g.scodoc_dept:
        query = query.join(FormSemestre).filter_by(dept_id=g.scodoc_dept_id)
    modimpl: ModuleImpl = query.first_or_404()
    return modimpl.to_dict(convert_objects=True)


@bp.route("/moduleimpl/<int:moduleimpl_id>/inscriptions")
@api_web_bp.route("/moduleimpl/<int:moduleimpl_id>/inscriptions")
@login_required
@scodoc
@permission_required(Permission.ScoView)
@as_json
def moduleimpl_inscriptions(moduleimpl_id: int):
    """Liste des inscriptions à ce moduleimpl
    Exemple de résultat :
        [
          {
            "id": 1,
            "etudid": 666,
            "moduleimpl_id": 1234,
          },
          ...
        ]
    """
    query = ModuleImpl.query.filter_by(id=moduleimpl_id)
    if g.scodoc_dept:
        query = query.join(FormSemestre).filter_by(dept_id=g.scodoc_dept_id)
    modimpl: ModuleImpl = query.first_or_404()
    return [i.to_dict() for i in modimpl.inscriptions]
