#!/usr/bin/env python
#-*- coding: utf-8 -*-

from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from swyzxwb_photovote.common.DataConvert import UniqueID

# Create your models here.
class PermissionList(models.Model):
    name = models.CharField(max_length=64)
    url = models.CharField(max_length=255)

    def __unicode__(self):
        return '%s(%s)' %(self.name,self.url)
                                              
class RoleList(models.Model):
    name = models.CharField(max_length=64)
    permission = models.ManyToManyField(PermissionList,null=True,blank=True)

    def __unicode__(self):
        return self.name

class UserManager(BaseUserManager):
    def create_user(self,sid,classid,username,password=None):
        if sid==None:
            raise ValueError('Users must have an student id!')
        if classid==None:
            raise ValueError('Users must have an class id!')
        user = self.model(
            sid = sid,
            classid = classid,
            username = username,
            importid = UniqueID()
        )

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

    def create_superuser(self,sid,classid,username,password):
        user = self.create_user(
            username = username,
            password = password,
            classid=classid,
            sid=sid,
            importid = UniqueID()
        )

        user.is_active = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

class GroupList(models.Model):
    name = models.CharField(max_length=64)
    classid = models.IntegerField(db_index=True,unique=True)
    #users = models.ManyToManyField(User,null=True,blank=True)

    def __unicode__(self):
        return self.name

class GroupListList(models.Model):
    classid = models.ManyToManyField(GroupList,null=True,blank=True)


class User(AbstractBaseUser):
    username = models.CharField(max_length=40, unique=True, db_index=True)
    sid = models.IntegerField(unique=True, db_index=True)
    classid = models.ForeignKey(GroupList,null=True,blank=True)
    email = models.EmailField(max_length=255, null=True ,blank=True)
    is_active = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    nickname = models.CharField(max_length=64, null=True)
    sex = models.CharField(max_length=2, null=True)
    role = models.ForeignKey(RoleList,null=True,blank=True)
    birthday = models.DateField(null=True,blank=True)
    importid = models.IntegerField(unique=False)
    
    
    objects = UserManager()
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['sid','classid','importid']

    def has_perm(self,perm,obj=None):
        if self.is_active and self.is_superuser:
            return True



