"""Test models referentiel compétences

Utiliser par exemple comme: 
    pytest tests/unit/test_refcomp.py

"""

from flask import g

from app import db
from app import models
from app.but.import_refcomp import orebut_import_refcomp
from app.models import UniteEns
from app.models.but_refcomp import (
    ApcReferentielCompetences,
    ApcCompetence,
    ApcSituationPro,
    ApcNiveau,
)
from app.models.formations import Formation

from tests.unit import setup

REF_RT_XML = open(
    "ressources/referentiels/but2022/competences/but-RT-05012022-081735.xml"
).read()


def test_but_refcomp(test_client):
    """modèles ref. comp."""
    dept_id = models.Departement.query.first().id
    ref_comp: ApcReferentielCompetences = orebut_import_refcomp(REF_RT_XML, dept_id)
    assert ref_comp.competences.count() == 13
    assert ref_comp.competences[0].situations.count() == 3
    assert ref_comp.competences[0].situations[0].libelle.startswith("Conception ")
    assert (
        ref_comp.competences[-1].situations[-1].libelle
        == "Administration des services multimédia"
    )
    # test cascades on delete
    db.session.delete(ref_comp)
    db.session.commit()
    assert ApcCompetence.query.count() == 0
    assert ApcSituationPro.query.count() == 0


def test_but_assoc_ue_parcours(test_client):
    """Association UE / Niveau compétence"""
    dept_id = models.Departement.query.first().id
    G, formation_id, (ue1_id, ue2_id, ue3_id), module_ids = setup.build_formation_test()
    ref_comp: ApcReferentielCompetences = orebut_import_refcomp(REF_RT_XML, dept_id)
    ue = UniteEns.query.get(ue1_id)
    assert ue.niveau_competence is None
    niveau = ApcNiveau.query.first()
    ue.niveau_competence = niveau
    db.session.add(ue)
    db.session.commit()
    ue = UniteEns.query.get(ue1_id)
    assert ue.niveau_competence == niveau
    assert len(niveau.ues) == 1
    assert niveau.ues[0] == ue


def test_but_assoc_refcomp(test_client):
    """Association formation / référentiel de compétences"""
    dept_id = models.Departement.query.first().id
    G, formation_id, (ue1_id, ue2_id, ue3_id), module_ids = setup.build_formation_test()
    formation: Formation = Formation.query.get(formation_id)
    assert formation is not None
    ref_comp: ApcReferentielCompetences = orebut_import_refcomp(REF_RT_XML, dept_id)
    formation.referentiel_competence_id = ref_comp.id
    db.session.add(formation)
    db.session.commit()
    ue = UniteEns.query.get(ue1_id)
    niveau = (
        ApcNiveau.query.filter_by(annee="BUT1")
        .join(ApcCompetence)
        .filter_by(referentiel_id=ref_comp.id)
        .first()
    )
    assert niveau is not None
    ue.niveau_competence_id = niveau.id
    db.session.add(ue)
    db.session.commit()
    formation.refcomp_desassoc()
    assert ue.niveau_competence_id is None
