from django.conf import settings
from django.contrib import admin
from django.contrib.auth.models import User, UserManager, Group
from django.db import models
from django.db.models.signals import post_save
from sorl.thumbnail import ImageField
import datetime

        
class Ldt(User):
#    irigroups = models.ManyToManyField(IriGroup, blank=True)
    
    class Meta:
        verbose_name = 'iri user'
        verbose_name_plural = 'iri users'
    
    def __unicode__(self):
        return self.username
        

class LdtManager(UserManager):
    def create_user(self, username, email, password=None):
        "Creates and saves a User with the given username, e-mail and password."
        now = datetime.datetime.utcnow()
        new_user = Ldt(None, username, '', '', email.strip().lower(), 'placeholder', False, True, False, now, now)
        if password:
            new_user.set_password(password)
        else:
            new_user.set_unusable_password()
        new_user.save()
        new_user.groups.add(Group.objects.get(name=settings.PUBLIC_GROUP_NAME))
        return new_user   
    
    
class UserProfile (models.Model): 
    user = models.OneToOneField(User)
    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)

    @staticmethod
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            UserProfile.objects.create(user=instance)

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()
            instance.user_set.add(User.objects.filter(is_superuser=True)[0])            
            
# To keep consistency with User.get_profile() method
def get_profile(self):
    return self.profile

Group.add_to_class("get_profile", get_profile)

post_save.connect(GroupProfile.create_group_profile, sender=Group)
post_save.connect(UserProfile.create_user_profile, sender=User)
   
User.objects = LdtManager()
User.objects.contribute_to_class(User, "objects")

admin.site.register(Ldt)
