import csv
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
    ue = None
    etudiantUes = etudiants = EtudiantUe.objects.none()
    typeEvaluations = TypeEvaluation.objects.all()
    typeEvaluationId = typeEvaluations.last().id
    sessions = Session.objects.all()
    sessionId = sessions.first().id
    evaluation = None
    listEvaluations = Evaluation.objects.none()
    search = ""
    notes = None
    disabled : bool = True
    fichier = None

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


    def resetNotesKey(self):
        self.notes = {}
        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()
        print(self.evaluation)


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

        self.resetNotesKey()
        self.noteBocking()


    def noteBocking(self):
        notes = Note.objects.filter(evaluation__ecue__id=self.ecueId)
        last_note = notes.last() 
        first_note = notes.first() 
        
        if notes and (last_note.evaluation.session.id == first_note.evaluation.session.id) and (last_note.evaluation.session.id == int(self.sessionId)) and last_note.isBlocked:
            self.disabled = True
        else:
            self.disabled = False



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



    def updated_typeEvaluationId(self, value: int):
        self.typeEvaluationId = value
        if value == '2':
            self.sessionId = 1

        self.resetEvaluations()



        
    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.resetEvaluations()
        self.call('notification', 'success', 'Toutes les notes ont ete enregistrer avec success')
       

    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, self.sessionId)
            
        self.resetEvaluations()
        self.call('notification', 'success', 'Toutes les notes ont ete enregistrer avec success')


    def deleteEvaluation(self, id):
        evaluation = Evaluation.objects.get(id=id)
        evaluation.delete()
        self.resetEvaluations()
        