# -*- coding: UTF-8 -*

"""Unit tests for caches


Ce test suppose une base département existante.

Usage: pytest tests/unit/test_caches.py
"""


from flask import g

import app
from app import db
from app.comp import res_sem
from app.comp.res_compat import NotesTableCompat
from app.models import Evaluation, FormSemestre, ModuleImpl
from app.scodoc import sco_cache
from app.scodoc import sco_evaluations
from app.scodoc import sco_evaluation_db
from app.scodoc import sco_formsemestre
from config import TestConfig
from tests.unit.test_sco_basic import run_sco_basic

DEPT = TestConfig.DEPT_TEST


def test_notes_table(test_client):  # XXX A REVOIR POUR TESTER RES TODO
    """Test construction et cache de NotesTable."""
    app.set_sco_dept(DEPT)
    assert g.scodoc_dept == DEPT
    # prépare le département avec quelques semestres:
    run_sco_basic()
    #
    sems = sco_formsemestre.do_formsemestre_list()
    assert len(sems)
    sem = sems[0]
    formsemestre_id = sem["formsemestre_id"]
    formsemestre: FormSemestre = FormSemestre.query.get_or_404(formsemestre_id)
    nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
    assert nt
    assert sco_cache.ResultatsSemestreCache.get(formsemestre_id)
    sco_cache.invalidate_formsemestre(formsemestre_id)
    assert not sco_cache.ResultatsSemestreCache.get(formsemestre_id)
    # cache les 10 premiers
    for sem in sems[:10]:
        formsemestre_id = sem["formsemestre_id"]
        nt: NotesTableCompat = res_sem.load_formsemestre_results(formsemestre)
        assert sco_cache.ResultatsSemestreCache.get(formsemestre_id)


def test_cache_evaluations(test_client):
    """"""
    # cherche un semestre ayant des evaluations
    app.set_sco_dept(DEPT)
    # prépare le département avec quelques semestres:
    run_sco_basic()
    #
    formsemestres = FormSemestre.query
    assert formsemestres.count()
    evaluation = None
    for formsemestre in formsemestres:
        evaluation: Evaluation = (
            Evaluation.query.join(ModuleImpl)
            .filter_by(formsemestre_id=formsemestre.id)
            .first()
        )
        if evaluation is not None:
            break
    if evaluation is None:
        raise Exception("no evaluations")
    #
    eval_notes = sco_evaluation_db.do_evaluation_get_all_notes(evaluation.id)
    # should have been be cached, except if empty
    if eval_notes:
        assert sco_cache.EvaluationCache.get(evaluation.id)
    sco_cache.invalidate_formsemestre(evaluation.moduleimpl.formsemestre.id)
    # should have been erased from cache:
    assert not sco_cache.EvaluationCache.get(evaluation.id)