# -*- coding: UTF-8 -*

"""ScoDoc models: evaluations
"""
from typing import Any

from app import db
from app.models import APO_CODE_STR_LEN
from app.models import SHORT_STR_LEN
from app.models import CODE_STR_LEN
from app.models import UniteEns

import app.scodoc.notesdb as ndb
from app.scodoc import sco_evaluation_db


class Evaluation(db.Model):
    """Evaluation (contrôle, examen, ...)"""

    __tablename__ = "notes_evaluation"

    id = db.Column(db.Integer, primary_key=True)
    evaluation_id = db.synonym("id")
    moduleimpl_id = db.Column(
        db.Integer, db.ForeignKey("notes_moduleimpl.id"), index=True
    )
    jour = db.Column(db.Date)
    heure_debut = db.Column(db.Time)
    heure_fin = db.Column(db.Time)
    description = db.Column(db.Text)
    note_max = db.Column(db.Float)
    coefficient = db.Column(db.Float)
    visibulletin = db.Column(
        db.Boolean, nullable=False, default=True, server_default="true"
    )
    publish_incomplete = db.Column(
        db.Boolean, nullable=False, default=False, server_default="false"
    )
    # type d'evaluation: 0 normale, 1 rattrapage, 2 "2eme session"
    evaluation_type = db.Column(
        db.Integer, nullable=False, default=0, server_default="0"
    )
    # ordre de presentation (par défaut, le plus petit numero
    # est la plus ancienne eval):
    numero = db.Column(db.Integer)
    ues = db.relationship("UniteEns", secondary="evaluation_ue_poids", viewonly=True)

    def to_dict(self):
        e = dict(self.__dict__)
        e.pop("_sa_instance_state", None)
        # ScoDoc7 output_formators
        e["jour"] = ndb.DateISOtoDMY(e["jour"])
        e["numero"] = ndb.int_null_is_zero(e["numero"])
        return sco_evaluation_db.evaluation_enrich_dict(e)

    # def from_dict(self, data):
    #     """Set evaluation attributes from given dict values."""
    #     sco_evaluation_db._check_evaluation_args(data)
    #     for field in [
    #         "moduleimpl_id",
    #         "jour",
    #         "heure_debut",
    #         "heure_fin",
    #         "description",
    #         "note_max",
    #         "coefficient",
    #         "visibulletin",
    #         "publish_incomplete",
    #         "evaluation_type",
    #         "numero",
    #     ]:
    #         if field in data:
    #             setattr(self, field, data[field] or None)

    def set_ue_poids(self, ue, poids: float):
        """Set poids évaluation vers cette UE"""
        self.update_ue_poids_dict({ue.id: poids})

    def set_ue_poids_dict(self, ue_poids_dict: dict):
        """set poids vers les UE (remplace existants)
        ue_poids_dict = { ue_id : poids }
        """
        L = []
        for ue_id, poids in ue_poids_dict.items():
            ue = UniteEns.query.get(ue_id)
            L.append(EvaluationUEPoids(evaluation=self, ue=ue, poids=poids))
        self.ue_poids = L

    def update_ue_poids_dict(self, ue_poids_dict: dict):
        """update poids vers UE (ajoute aux existants)"""
        current = self.get_ue_poids_dict()
        current.update(ue_poids_dict)
        self.set_ue_poids_dict(current)

    def get_ue_poids_dict(self):
        """returns { ue_id : poids }"""
        return {p.ue.id: p.poids for p in self.ue_poids}


class EvaluationUEPoids(db.Model):
    """Poids des évaluations (BUT)
    association many to many
    """

    evaluation_id = db.Column(
        db.Integer, db.ForeignKey("notes_evaluation.id"), primary_key=True
    )
    ue_id = db.Column(db.Integer, db.ForeignKey("notes_ue.id"), primary_key=True)
    poids = db.Column(
        db.Float,
        nullable=False,
    )
    evaluation = db.relationship(
        Evaluation,
        backref=db.backref("ue_poids", cascade="all, delete-orphan"),
    )
    ue = db.relationship(
        UniteEns,
        backref=db.backref("evaluation_ue_poids", cascade="all, delete-orphan"),
    )

    def __repr__(self):
        return f"<EvaluationUEPoids {self.evaluation} {self.ue} poids={self.poids}>"
