from django_unicorn.components import UnicornView
from django.db.utils import IntegrityError
from django.contrib import messages
from numpy import empty
from BasicData.models import Annee, Ecue, EtudiantUe, Evaluation, Note, ParcoursSemestreUe, Session, TypeEvaluation
from EspaceEnseignant.calculer_moyenne import calcul

class NoteComponentView(UnicornView):
    ecueId = None
    etudiantUes = etudiants = EtudiantUe.objects.none()
    typeEvaluations = TypeEvaluation.objects.all()
    typeEvaluationId = None
    sessions = Session.objects.all()
    sessionId = 0
    evaluation = None
    listEvaluations = Evaluation.objects.none()
    search = ""
    notes = {}
    isValidate = False
    disabled : bool = True

    def mount(self):
        ue = Ecue.objects.get(pk=self.ecueId).ue
        parcourSemestreUe = ParcoursSemestreUe.objects.filter(ue=ue, annee=Annee.objects.last()).first()
        self.etudiantUes = EtudiantUe.objects.filter(parcoursSemestreUe=parcourSemestreUe)


    def resetNotesKey(self):
        self.notes.clear()
        for etuUe in self.etudiantUes:
            self.notes[str(etuUe.etudiant.id)] = {}
            for eval in self.listEvaluations:
                res = None
                try:
                    note = Note.objects.get(etudiant=etuUe.etudiant, evaluation=eval)
                    res = {str(eval.id): note.note}
                except Note.DoesNotExist:
                    res = {str(eval.id): None} 
                
                self.notes[str(etuUe.etudiant.id)].update(res)
        

    def saveEvaluation(self):
        try:
            Evaluation.objects.create(
                libelle=self.evaluation, 
                session_id=self.sessionId, 
                typeEvaluation_id=self.typeEvaluationId,
                annee=Annee.objects.last(),
                ecue_id=self.ecueId
            )
        except IntegrityError:
            messages.error(self.request, "Velliez selectionner un type d'evaluation et une session svp.")


        self.evaluation = None
        self.resetEvaluations()


    def resetEvaluations(self):
        self.listEvaluations = Evaluation.objects.filter(
            annee=Annee.objects.last(), 
            ecue_id=self.ecueId, 
            session_id=self.sessionId
        )

        self.resetNotesKey()

        note = Note.objects.filter(evaluation__ecue__id=self.ecueId)
        last_note = note.last() 
        first_note = note.first()

        
        if note:
            if (last_note.evaluation.session.id == first_note.evaluation.session.id):
                if last_note.isBlocked:
                    self.disabled = True
                    print()
                    print(self.disabled)
                    print()
                else:
                    self.disabled = False

            elif (last_note.evaluation.session.id == int(self.sessionId)):
                if last_note.isBlocked:
                    self.disabled = True
                else:
                    self.disabled = False
            else:
                self.disabled = False
        else:
            self.disabled = False



    def updated_sessionId(self, value):
        self.sessionId = value
        self.resetEvaluations()



    def updated_typeEvaluationId(self, value):
        self.typeEvaluationId = value

    def enregistrer(self):
        for etuId, evalNote in self.notes.items():
            for evalId, note in evalNote.items():
                if note:
                    newNote, res = Note.objects.get_or_create(etudiant_id=etuId, evaluation_id=evalId)
                    newNote.note = note
                    newNote.save()
                    

        self.isValidate = True
        self.resetEvaluations()
       

    def valider(self):
        self.enregistrer()
        for etuId, evalNote in self.notes.items():
            for evalId in evalNote.keys():
                try:
                    note = Note.objects.get(etudiant_id=etuId, evaluation_id=evalId)
                    note.isBlocked=True
                    note.save()
                except Note.DoesNotExist:
                    pass
            
            calcul(etuId, self.ecueId)

        