# -*- coding: utf-8 -*-

"""
Proxy User Model
"""

from django.db import models
from django.contrib.auth.models import User as AuthUser, Group
from django.utils.translation import ugettext_lazy as _

class PolynumUser(AuthUser):
    def get_ldap_attributes(self):
        from polynum.base.backends import CASBackend
        return CASBackend().get_ldap_attributes(self)

    def display_name(self):
        name = self.get_full_name().strip()
        if name:
            return name
        return self.username

    def get_preferred_entities(self):
        return []

    def get_preferred_financial_codes(self):
        return []

    def has_roles(self):
        return self.roleassociation_set.exists()

    def has_role_reprography(self):
        return self.roleassociation_set.filter(role__id='reprography').exists()

    def update_groups_from_roles(self):
        roles = rbac.Role.objects.all()
        def names(qs):
            return qs.distinct().values_list('name')
        to_add = names(roles.filter(roleassociation__user=self))
        to_remove = names(roles.exclude(roleassociation__user=self))
        group_to_keep = self.groups.exclude(name__in=to_remove)
        group_to_add = Group.objects.filter(name__in=to_add)
        new_groups = group_to_keep | group_to_add
        self.groups = list(new_groups)
        if new_groups:
            self.is_staff = True
            self.save()
        elif not self.is_superuser and not self.groups:
            self.is_staff = False
            self.save()

    def __unicode__(self):
        return self.display_name()

    class Meta:
        proxy = True
        app_label = 'auth'
        verbose_name = _(u'Utilisateur')
User = PolynumUser

import rbac
from django.db.models.signals import post_save, post_delete

from django.dispatch import receiver


"""Try to maintain user/group link based on similar names for groups and roles"""

def update_user_groups_on_users_after_role_association_change(sender, 
        instance, **kwargs):
    role_association = instance
    role_association.user.update_groups_from_roles()

post_save.connect(update_user_groups_on_users_after_role_association_change,
        sender=rbac.RoleAssociation)
post_delete.connect(update_user_groups_on_users_after_role_association_change,
        sender=rbac.RoleAssociation)

@receiver(post_save, sender=Group)
def update_user_groups_on_user_after_group_creation(sender,
        instance, **kwargs):
    group = instance
    for user in User.objects.filter(roleassociation__role__name=group.name):
        user.update_groups_from_roles()

@receiver(post_save, sender=rbac.Role)
def update_user_groups_on_role_modification(sender,
        instance, **kwargs):
    role = instance
    for user in User.objects.filter(roleassociation__role=role):
        user.update_groups_from_roles()

class PolynumProfile(models.Model):
    user = models.OneToOneField(AuthUser)
    phone = models.CharField(max_length=32, verbose_name=_(u'Téléphone'),
            default='')
    accepted_cgu = models.BooleanField(
            verbose_name=_(u"A accepté les conditions générales "
                "d'utilisation"),
            blank=True, default=False)

    class Meta:
        app_label = 'base'
