from django.contrib.auth.models import User
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.contrib import admin
import uuid

EVAL_TYPE = [
    ('1', 'Intervention'),
    ('2', 'Journée'),
    ('3','Exercice')
]
INTER_NATURE = [
    ('1', 'Trauma'),
    ('2', 'non-Trauma'),
]
INTER_PRIORITY = [
    ('1', 'P1'),
    ('2', 'P2'),
    ('3', 'P3'),
    ('4', 'S1'),
    ('5', 'S2'),
    ('6', 'S3'),
    ('7', 'Exercice'),
]
INTER_COMPLEXITY = [
    ('1', 'Stable / Simple'),
    ('2', 'Stable / Complexe'),
    ('3', 'Instable / Simple'),
    ('4', 'Instable / Complexe'),
]

STUDENT_ROLE = [
    ('1', 'Leader'),
    ('2', 'Équipier'),
    ('3', '3e position (observateur)'),
]

EVAL_MODE = [
    ('1', 'Auto-évaluation'),
    ('2', 'Encadrant'),
]
def increment_ID():
    obj = cl_Student_eval.objects.all().order_by('ID').last()

    if obj is None:
        return 1

    last_id = int(obj.ID)
    return last_id + 1

class cl_Student_eval(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True)
    ID = models.IntegerField("ID du Suivi", editable=False, unique=True, default=increment_ID)

    # Informations sur l'auteur
    Author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="Auteur", on_delete=models.SET_NULL, null=True, related_name="eval_author")
    sAuthor = models.CharField("Auteur", max_length=120)
    Author_2e = models.ForeignKey(settings.AUTH_USER_MODEL,limit_choices_to={'groups__name': "Intervenants-Monthey"}, verbose_name="Co-auteur", on_delete=models.SET_NULL, null=True, related_name="eval_second_author", blank=True,)
    sAuthor_2e = models.CharField("Co-auteur", max_length=120, blank=True,)

    #Information sur l 'étudiant/stagiaire
    Student = models.ForeignKey(settings.AUTH_USER_MODEL,limit_choices_to={'groups__name': "FI-Étudiants"}, verbose_name="Nom du stagiaire/étudaint", on_delete=models.SET_NULL, null=True)
    sStudent = models.CharField("Nom de l'étudiant/stagiaire", max_length=120)

    #Information sur le suivi
    nEval_Type = models.CharField('Type de suivi', max_length=1, choices=EVAL_TYPE, default=0)
    dtDate = models.DateField("Date concernée", default=timezone.now)
    sRef = models.CharField("N° de référence / FIP / Date de la journée", max_length=120)
    nEval_Mode = models.CharField('Mode de suivi ', max_length=1, choices=EVAL_MODE, default=0)
    sDesc_neg = models.TextField("Points à améliorer")
    sDesc_pos = models.TextField("Points positifs")
    sDesc_global = models.TextField("Avis global sur l'intervention/journée/exercice")

    #Information sur l'intervention
    nInter_Nature = models.CharField('Nature', max_length=1, choices=INTER_NATURE, default=0, blank=True,)
    nInter_Priority = models.CharField('Priorité', max_length=1, choices=INTER_PRIORITY, default=0, blank=True,)
    nInter_Complexity = models.CharField('Nature de complexité', max_length=1, choices=INTER_COMPLEXITY, default=0, blank=True,)
    sInter_Desc = models.TextField("Description courte", blank=True,)
    nStudent_Role = models.CharField("Rôle de l'étudiant/stagiaire", max_length=1, choices=STUDENT_ROLE, default=0, blank=True,)


    #Automatic data
    dtUpdated = models.DateTimeField('date updated', auto_now=True)
    dtCreated = models.DateTimeField('date published', auto_now_add=True)


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.a_evals = None

        self.o_Auto_eval = None
        self.o_Encadrant_eval = None
        self.mirrored = False



    @admin.display(description='Référence du suivi')
    def get_ref_of_eval(self):
        sRet = ""

        if int(self.nEval_Type) == 2:
            sRet = self.dtDate.strftime("%d.%b.%Y")
        else:
            sRet = self.sRef
        


        #print(sRet)
        #print(f"Eval_Type = {self.nEval_Type} => {int(self.nEval_Type)-1}")
        return f"{EVAL_TYPE[int(self.nEval_Type)-1][1]}: {sRet}"

    def get_mirror_eval(self, evals):
        #print(self)
        for eval in evals:
            eval = eval["eval"]

            to_be_set = False
            if eval.ID == self.ID:
                to_be_set = True
            else:
                print("check eval")
                print(eval)
                print(self)
                
                if eval.nEval_Type == "1" and eval.sRef == self.sRef:
                    print(f"Eval mirror found type 1 {eval} / {self}")
                    to_be_set = True
                elif eval.nEval_Type == "2" and eval.sRef == self.sRef:
                    print(f"Eval mirror found type 2 {eval} / {self}")
                    to_be_set = True
                if eval.nEval_Type == "3" and eval.sRef == self.sRef:
                    print(f"Eval mirror found type 3 {eval} / {self}")
                    to_be_set = True

            if to_be_set:
                if eval.nEval_Mode == "1":
                    self.o_Auto_eval = eval
                elif eval.nEval_Mode == "2":
                    self.o_Encadrant_eval = eval



        if self.o_Encadrant_eval is not None and self.o_Auto_eval is not None:
            self.mirrored = True
            print(f" auto = {self.o_Auto_eval} / encadrant = {self.o_Encadrant_eval}")


    def get_all_evals_for_student(self,sStudent=None):
        if sStudent is None:
            sStudent = self.sStudent

        print(f"get_all_evals_for_student launched ! {sStudent}")

        self.a_evals = []
        evals = cl_Student_eval.objects.filter(sStudent=sStudent).order_by('sRef')
        for eval in evals:
            self.a_evals.append({"uuid":eval.uuid,"sRef":eval.sRef, "nEval_Mode": eval.nEval_Mode, "nEval_Type": eval.nEval_Type, "eval":eval, "dtDate": eval.dtDate})


       #print(self.a_evals)
        return self.a_evals

    @admin.display(description="Mirroir ?", boolean=True)
    def get_mirrored(self):
        self.get_all_evals_for_student()
        self.get_mirror_eval(self.a_evals)
        return self.mirrored


    def get_inter_priority(self):
        try:
            return INTER_PRIORITY[int(self.nInter_Priority) - 1][1]
        except:
            return f"Unknown {self.nInter_Priority}"

    def get_eval_mode(self):
        try:
            return EVAL_MODE[int(self.nEval_Mode) - 1][1]
        except:
            return f"Unknown {self.nEval_Mode}"

    def get_student_role(self):
        try:
            return STUDENT_ROLE[int(self.nStudent_Role) - 1][1]
        except:
            return f"Unknown {self.nStudent_Role}"

    def get_inter_nature(self):
        try:
            return INTER_NATURE[int(self.nInter_Nature) - 1][1]
        except:
            return f"Unknown {self.nInter_Nature}"

    def get_eval_type(self):
        try:
            return EVAL_TYPE[int(self.nEval_Type) - 1][1]
        except:
            return f"Unknown {self.nEval_Type}"

    def get_inter_complexity(self):
        try:
            return INTER_COMPLEXITY[int(self.nInter_Complexity) - 1][1]
        except:
            return f"Unknown {self.nInter_Complexity}"

    def __str__(self):
        try:
            return f"#{self.ID} { self.sStudent } => {self.get_ref_of_eval()} ({EVAL_MODE[int(self.nEval_Mode)-1][1]} / {EVAL_TYPE[int(self.nEval_Type)-1][1]})"
        except:
            return ""

    class Meta:
        verbose_name = "Suivi étudiants"
        verbose_name_plural = "Suivis étudiants"
        ordering = ["-ID"]


import csv
import os
from datetime import datetime
from django.core.exceptions import ValidationError

chemin_actuel = os.path.dirname(__file__)
def import_data_csv():
    with open(os.path.join(chemin_actuel, 'import.csv'), 'r', encoding='utf-8') as file_csv:
        file_csv = csv.DictReader(file_csv)
        first_line = True
        for line in file_csv:
            # Ne rien faire avec la première ligne = Header


            new_eval = cl_Student_eval()

            for key in line.keys():
                if key == "Zeitstempel":
                    continue
                value = line[key]
                if key == "dtDate":
                    value = datetime.strptime(value, "%d.%m.%Y").date()
                elif key == "Student" and value != "":
                    print(f"user == pk{value}")
                    try:
                        temp_user = User.objects.get(pk=int(value))
                        setattr(new_eval, "Student", temp_user)
                    except:
                        print(f"User not found {int(value)} {line}")
                        pass
                    continue
                elif key == "ID":
                    pass

                if key in ["nEval_Type","nInter_Priority","nInter_Nature","nInter_Complexity","nStudent_Role","nEval_Mode"]:
                    print(f"key [{key}] => {value}")
                    value = int(value) if value != "" else ""

                setattr(new_eval, key,value)
            print(f"try to save {line}")
            try:
                new_eval.save()
                print(f"Save new eval {new_eval.ID}")
            except:
                print(f"Error to save {new_eval.ID}")

#import_data_csv()