from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from django.utils.translation import ugettext_lazy as _

from core.models import ContactDataBase, PersonBase, WinoseBaseWithTrackingModel


class WinoseUserManager(BaseUserManager):
    def create_user(self, username, email, password=None, first_name=None, last_name=None):
        user = self.model(username=username,
                          email=email,
                          first_name=first_name,
                          last_name=last_name)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, email, password=None, first_name=None, last_name=None):
        user = self.model(username=username,
                          email=email,
                          first_name=first_name,
                          last_name=last_name)
        user.is_superuser = True
        user.set_password(password)
        user.save(using=self._db)
        return user


LAB_GROUP_ID = 'A'
HEAD_OF_LAB_ID = 'L'
QUALITY_MANAGER_ID = 'Z'

USERGROUP_CHOICES = [
    (LAB_GROUP_ID, _('lab technician')),
    (HEAD_OF_LAB_ID, _('head of olfactometry'))
    # (QUALITY_MANAGER_ID, _('quality management'))
]


class WinoseUser(AbstractBaseUser, WinoseBaseWithTrackingModel, ContactDataBase, PersonBase):
    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    overview_url = 'users_list'
    create_url = 'user_create'
    detail_url = 'user_detail'
    update_url = 'user_update'

    objects = WinoseUserManager()

    username = models.CharField(
        max_length=31,
        verbose_name=_('user name'),
        unique=True
    )

    user_group = models.CharField(choices=USERGROUP_CHOICES, max_length=1, blank=True)
    is_superuser = models.BooleanField(blank=False, default=False)

    # optional signature
    signature = models.ImageField(
        null=True,
        blank=True,
        upload_to='images',
        verbose_name=_('signature')
    )

    position = models.CharField(max_length=127,
                                blank=True,
                                null=False,
                                default='',
                                verbose_name=_('position/job title'))

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['first_name', 'last_name']

