from django.db import models
from django.contrib.auth.models import User
import os
from tinymce import models as tinymce_models
from model_utils import Choices
import qrcode
from io import BytesIO
from django.core.files import File
from PIL import Image, ImageDraw
from universidad.models import carrera

# Create your models here.

class perfil(models.Model):
    TIPO = Choices('Estudiante', 'Docente', 'Administrativo', 'Visitante')
    GENERO = Choices('M', 'F')
    GRU = Choices('A','B','C','D')
    CUATRI = Choices('0','1','2','3','4','5','6','7','8','9','10')
    usuario = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    matricula = models.CharField(max_length=50, unique=True, null=False, blank=False, verbose_name='Matricula ó CURP')
    cuatrimestre = models.CharField(choices=CUATRI, default=0, max_length=2, verbose_name='Cuatrimestre')
    grupo = models.CharField(choices=GRU, default=GRU.A, max_length=1, verbose_name='Grupo')
    direccion = models.CharField(max_length=250, null=True, blank=True, verbose_name='Domicilio')
    genero = models.CharField(choices=GENERO, default=GENERO.M, max_length=1, verbose_name='Genero')
    telefono = models.CharField(max_length=15, null=True, blank=True, verbose_name='Telefono')
    tipo = models.CharField(choices=TIPO, default=TIPO.Estudiante, max_length=20, verbose_name='Tipo')
    id_carrera = models.ForeignKey(carrera, on_delete=models.CASCADE, null=False, blank=False, verbose_name='Carrera')
    foto = models.ImageField(upload_to='foto/', blank=True)
    qr = models.ImageField(upload_to='qr/', blank=True)
    fecha_alta = models.DateField(auto_now_add=True, verbose_name='Fecha alta')
    fecha_actualizacion = models.DateField(auto_now=True, verbose_name='Fecha de Actualización')
    key = models.CharField(max_length=250, null=True, blank=True, verbose_name='Key')
        
    def delete(self, *args, **kwargs):
        if os.path.isfile(self.foto.path):
            os.remove(self.foto.path)
        super(perfil, self).delete(*args, **kwargs)
    
    def __str__(self):
        return self.matricula
    
    def save(self, *args, **kwargs):
        data =  self.key
        key = ''.join(ch for ch in data if ch.isalnum())
        qr_image = qrcode.make(key)
        qr_offset = Image.new('RGB',(480, 480),'white')
        qr_offset.paste(qr_image)
        files_name = f'{self.matricula}qr.png'
        stream = BytesIO()
        qr_offset.save(stream, 'PNG')
        self.qr.save(files_name, File(stream), save=False)
        qr_offset.close()
        super().save(*args, **kwargs)

    
    class Meta:
        verbose_name = 'perfil'
        verbose_name_plural = 'perfiles'
        ordering = ['matricula']