from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin

from tagulous.models import TagTreeModel

from companies.models import Company

# Create your models here.
class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_active', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)


class CustomUser(AbstractBaseUser, PermissionsMixin):

    SHOP_USER = 'SHOP_USER'
    COOP_MANAGER = 'COOP_MANAGER'
    SITE_ADMIN = 'SITE_ADMIN'

    ROLES = (
        (SHOP_USER, 'Shop User'),
        (COOP_MANAGER, 'Coop Manager'),
        (SITE_ADMIN, 'Site Admin'),
    )

    email = models.EmailField('Dirección de email', unique=True)
    full_name = models.CharField('Nombre completo', max_length=100, blank=True)
    role = models.CharField('Rol', choices=ROLES, default=SHOP_USER, max_length=100, blank=True, null=True)
    notify = models.BooleanField('Notificar', default=False, null=True)
    provider = models.CharField('Proveedor', max_length=1000, blank=True, null=True) # red social de registro
    email_verified = models.BooleanField('Email verificado', default=False, null=True)
    company = models.ForeignKey(Company, null=True, blank=True, on_delete=models.DO_NOTHING, related_name='custom_user')

    is_active = models.BooleanField('Activo', default=True)
    is_staff = models.BooleanField('Empleado',default=False )

    modified = models.DateTimeField(auto_now=True, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    last_visit = models.DateTimeField(auto_now=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = 'Usuario'
        verbose_name_plural = 'Usuarios'

