# coding=utf-8
from __future__ import unicode_literals

from django.contrib.auth.models import BaseUserManager
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from django.db.models import Q

get_content_type = ContentType.objects.get_for_model


class UserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)

        user = self.model(
            email=self.normalize_email(email),
            **extra_fields
        )
        if password:
            user.set_password(password)
        else:
            user.password = ''

        user.save(using=self._db)
        return user

    def get_or_create(self, **kwargs):
        if "email" in kwargs:
            email = kwargs["email"]
        else:
            raise ValueError("email is required")
        try:
            user = self.model.objects.get(email=email)
        except self.model.DoesNotExist:
            user = self.model(**kwargs)
            user.save()

        return user

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

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=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)
