"""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 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 multimé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