# coding: utf-8
from django.db import models


class RoleQuerySet(models.QuerySet):

    def approved(self):
        return self.filter(is_approved=True)


RoleManagerBase = models.Manager.from_queryset(RoleQuerySet)


class RoleManager(RoleManagerBase):

    def get_queryset(self):
        qs = super(RoleManager, self).get_queryset()
        # Нас интересуют только роли по фидбечнице
        return qs.filter(project=Role.PROJECT_FEEDBACK)


class Role(models.Model):
    """
    Базовая модель cia-роли.
    Пока что таблицы живут в отдельной БД - cia.
    """

    PROJECT_REVIEW = 'review'
    PROJECT_FEEDBACK = 'feedback'

    # FIXME: больше неактуально
    PROJECTS = (
        (PROJECT_REVIEW, PROJECT_REVIEW),
        (PROJECT_FEEDBACK, PROJECT_FEEDBACK),
    )

    ACTION_READ = 'read'
    ACTION_READ_SALARY = 'read_salary'
    ACTION_APPROVE = 'approve'

    # FIXME: больше неактуально, нужно было только для ревью
    ACTIONS = (
        (ACTION_READ, u'Просмотр повышений'),
        (ACTION_READ_SALARY, u'Просмотр повышений и зарплат'),
        (ACTION_APPROVE, u'Согласование'),
    )

    STATUS_NONE = 0
    STATUS_PROCESS_CREATE = 1
    STATUS_OK = 2
    STATUS_PROCESS_DELETE = 3

    STATUSES = (
        (STATUS_NONE, 'User created'),
        (STATUS_PROCESS_CREATE, 'Transfering to idm'),
        (STATUS_OK, 'In idm'),
        (STATUS_PROCESS_DELETE, 'Deleting from idm'),
    )

    owner = models.ForeignKey('staff.Person', related_name='%(app_label)s_%(class)s_as_owner')
    granter = models.ForeignKey('staff.Person', related_name='%(app_label)s_%(class)s_as_granter')
    requester = models.ForeignKey('staff.Person', related_name='%(app_label)s_%(class)s_as_requester')

    project = models.CharField(max_length=255, choices=PROJECTS)
    action = models.CharField(max_length=255, choices=ACTIONS)
    is_approved = models.BooleanField(default=False)

    # FIXME: нигде не используется сейчас
    idm_role_id = models.IntegerField(null=True)

    status = models.IntegerField(default=STATUS_NONE, choices=STATUSES)

    objects = RoleManager()

    class Meta:
        abstract = True

    @property
    def type(self):
        return self.__class__.__name__

    @property
    def role(self):
        return {}

    def as_idm_role(self):
        return [self.role, {}]

    @property
    def path(self):
        return '/{0.type}/'.format(self)

    @property
    def user(self):
        return self.owner.login

    @property
    def is_person_role(self):
        return isinstance(self, PersonRole)

    @property
    def is_group_role(self):
        return isinstance(self, GroupRole)


class PersonRole(Role):

    subject = models.ForeignKey('staff.Person', related_name='%(app_label)s_%(class)s_as_subject')

    class Meta:
        db_table = 'role_personrole'
        unique_together = ('owner', 'subject', 'granter', 'project', 'action')

    @property
    def role(self):
        return dict(
            # project=self.project,
            # action=self.action,
            subject=self.subject.login,
            granter=self.granter.login,
            type='PersonRole',
        )

    @property
    def path(self):
        return '/{type}/{subject}/{granter}/'.format(**self.role)


class GroupRole(Role):

    group = models.ForeignKey('staff.GroupDetails', related_name='roles')

    class Meta:
        db_table = 'role_grouprole'
        unique_together = ('owner', 'group', 'granter', 'project', 'action')

    @property
    def role(self):
        return dict(
            # project=self.project,
            # action=self.action,
            group=str(self.group.staff_id),
            granter=self.granter.login,
            type='GroupRole',
        )

    @property
    def path(self):
        return '/{type}/{group}/{granter}/'.format(**self.role)
