from crum import get_current_request
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.forms import model_to_dict

from config.settings import MEDIA_URL, STATIC_URL


class User(AbstractUser):
    image = models.ImageField(upload_to='users/%Y/%m/%d', null=True, blank=True)
    # token
    token = models.UUIDField(primary_key=False,  editable=False, null=True, blank=True)

    def get_image(self):
        if self.image:
            return '{}{}'.format(MEDIA_URL, self.image)
        return '{}{}'.format(STATIC_URL, 'img/empty.png')

    def toJSON(self):
        # se excluye la fecha de ultimo ingreso debidoa  la creacion de nuevo no tiene fecha
        item = model_to_dict(self, exclude=['password',  'user_permissions', 'last_login'])
        if self.last_login:
            item['last_login'] = self.last_login.strftime('%Y-%m-%d')
        item['date_joined'] = self.date_joined.strftime('%Y-%m-%d')
        item['image'] = self.get_image()
        item['full_name'] = self.get_full_name()
        item['groups'] = [ {'id':g.id, 'name':g.name} for g in  self.groups.all()]
        return item

# esto para poder encriptar la contrasenia cuando es primer ingreso pero no funxipno xd
#     def save(self, *args, **kwargs):
#         if self.pk is None:
#             self.set_password(self.password)
#         else:
#             user = User.objects.get(pk=self.pk)
#             if user.password != self.password:
#                 self.set_password(self.password)
#         super().save(*args, **kwargs)

    def get_group_session(self):
        try:
            # si tienen grupos
            request = get_current_request()
            groups = self.groups.all()
            if groups.exists():
                if 'group' not in request.session:
                    request.session['group'] = groups[0]
        except:
            pass

