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

"""Chargement des résultats de semestres (tous types)
"""
from flask import g

from app import db
from app.comp.jury import ValidationsSemestre
from app.comp.res_common import ResultatsSemestre
from app.comp.res_classic import ResultatsSemestreClassic
from app.comp.res_but import ResultatsSemestreBUT
from app.models.formsemestre import FormSemestre
from app.scodoc import sco_cache


def load_formsemestre_results(formsemestre: FormSemestre) -> ResultatsSemestre:
    """Returns ResultatsSemestre for this formsemestre.
    Suivant le type de formation, retour une instance de
    ResultatsSemestreClassic ou de ResultatsSemestreBUT.

    Search in local cache (g.formsemestre_result_cache)
    If not in cache, build it and cache it.
    """
    is_apc = formsemestre.formation.is_apc()
    if is_apc and formsemestre.semestre_id == -1:
        formsemestre.semestre_id = 1
        db.session.add(formsemestre)
        db.session.commit()
        sco_cache.invalidate_formsemestre(formsemestre.id)

    # --- Try local cache (within the same request context)
    if not hasattr(g, "formsemestre_results_cache"):
        g.formsemestre_results_cache = {}
    else:
        if formsemestre.id in g.formsemestre_results_cache:
            return g.formsemestre_results_cache[formsemestre.id]

    klass = ResultatsSemestreBUT if is_apc else ResultatsSemestreClassic
    g.formsemestre_results_cache[formsemestre.id] = klass(formsemestre)
    return g.formsemestre_results_cache[formsemestre.id]


def load_formsemestre_validations(formsemestre: FormSemestre) -> ValidationsSemestre:
    """Charge les résultats de jury de ce semestre.
    Search in local cache (g.formsemestre_result_cache)
    If not in cache, build it and cache it (in g).
    """
    if not hasattr(g, "formsemestre_validation_cache"):
        g.formsemestre_validations_cache = {}  # pylint: disable=C0237
    else:
        if formsemestre.id in g.formsemestre_validations_cache:
            return g.formsemestre_validations_cache[formsemestre.id]

    g.formsemestre_validations_cache[formsemestre.id] = ValidationsSemestre(
        formsemestre
    )
    return g.formsemestre_validations_cache[formsemestre.id]