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

identities = [
    ('user', 'user'),
    ('admin', 'administrator'),
]


class UserManager(BaseUserManager):
    def create_user(self, username, password):
        if password == None or username == None:
            raise ValueError("用户名或密码为空")
        user = self.model(
            username = username,
            displayname = username,
            identity = 'user',
        )
        user.set_password(password)
        user.save()
        return user
    
    def create_superuser(self, username, password):
        if password == None or username == None:
            raise ValueError("用户名或密码为空")
        user = self.model(
            username = username,
            displayname = username,
            identity = 'admin',
        )
        user.set_password(password)
        user.save()
        return user

# Create your models here.
class User(AbstractBaseUser):
    
    username = models.CharField(max_length=50, unique=True)
    password = models.CharField(max_length=100)
    displayname = models.CharField(max_length=32)
    create_time = models.DateField(auto_now_add=True)
    identity = models.CharField(default='user', max_length=16, choices=identities)
    
    objects = UserManager()
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []
    
    def is_admin(self):
        if self.identity == 'admin':
            return True
        else:
            return False
        
    class Meta:
        app_label = 'api'