from django.conf import settings
from django.contrib.auth.models import (AbstractUser, User, UserManager, Group, 
    BaseUserManager)
from django.db import models
from django.db.models.signals import post_save
from django.utils import timezone
from sorl.thumbnail import ImageField


class LdtUserManager(BaseUserManager):    

    def create_user(self, username, email=None, password=None, **extra_fields):
        """
        Creates and saves a User with the given username, email and password.
        """
        now = timezone.now()
        if not username:
            raise ValueError('The given username must be set')
        email = UserManager.normalize_email(email)
        user = self.model(username=username, email=email,
                          is_staff=False, is_active=True, is_superuser=False,
                          last_login=now, date_joined=now, **extra_fields)

        user.set_password(password)
        user.save(using=self._db)
        everyone, _ = Group.objects.get_or_create(name=settings.PUBLIC_GROUP_NAME)
        user.groups.add(everyone)
        return user

    def create_superuser(self, username, email, password, **extra_fields):
        u = self.create_user(username, email, password, **extra_fields)
        u.is_staff = True
        u.is_active = True
        u.is_superuser = True
        u.save(using=self._db)
        return u

class GroupProfile(models.Model):
    group = models.OneToOneField(Group, primary_key=False, related_name='profile')
    description = models.TextField()
    image = ImageField(upload_to=settings.MEDIA_ROOT+"thumbnails/groups/", default=settings.DEFAULT_GROUP_ICON, max_length=200)
    
    @staticmethod
    def create_group_profile(sender, instance, created, **kwargs):
        if created:
            profile = GroupProfile()
            profile.group_id = instance.id
            profile.save()
            admins = User.objects.filter(is_superuser=True)
            if admins:
                instance.user_set.add(admins[0])            

class LdtUser(AbstractUser):
    language = models.CharField(max_length=2, default=settings.LANGUAGE_CODE[:2])    
    image = ImageField(upload_to=settings.MEDIA_ROOT+"thumbnails/users/", default=settings.DEFAULT_USER_ICON, max_length=200)
    
    objects = LdtUserManager()

            
# To keep consistency with User.get_profile() method
def get_profile(self):
    return self.profile

Group.add_to_class("get_profile", get_profile)  # @UndefinedVariable
post_save.connect(GroupProfile.create_group_profile, sender=Group)

