from django.db import models
from django.utils.translation import ugettext_lazy as _

from idm.core.constants.approverequest import APPROVEREQUEST_DECISION
from idm.core.constants.workflow import DEFAULT_PRIORITY
from idm.core.querysets.approve import ApproveManager
from idm.framework.fields import StrictForeignKey


class Approve(models.Model):
    """Запрос на подтвержение роли.

    Может быть отправлен одному или нескольким
    получателям, любой из которых может подтвердить.
    """
    role_request = StrictForeignKey(
        'core.RoleRequest',
        verbose_name=_('Запрос'),
        related_name='approves',
        null=False,
        on_delete=models.CASCADE,
    )
    approved = models.NullBooleanField(_('Подтверждение получено'), null=True)
    main_priority = models.PositiveSmallIntegerField(blank=True, default=DEFAULT_PRIORITY,
                                                     verbose_name=_('Основной приоритет для группы подтверждающих'))

    objects = ApproveManager()

    class Meta:
        verbose_name = _('Группа подтверждающих')
        verbose_name_plural = _('Группы подтверждающих')
        db_table = 'upravlyator_approve'
        ordering = ('id',)

    def __str__(self):
        requests = ' | '.join(
            ':'.join((username, APPROVEREQUEST_DECISION.ABBREVIATION[decision]))
            for username, decision in self.requests.values_list('approver__username', 'decision')
        )
        return '%d, requester=%s, status=%s, %s' % (
            self.pk,
            self.role_request.requester.username if self.role_request.requester_id else 'auto-robot-idm',
            self.state,
            requests
        )

    @property
    def state(self):
        result = 'waiting'
        if self.approved is False:
            result = 'declined'
        elif self.approved is True:
            result = 'approved'
        return result

    def get_main_approvers(self):
        return [
            approve_request.approver
            for approve_request in self.requests.filter(priority__lte=self.main_priority).select_related('approver')
        ]

    def get_additional_approvers(self):
        return [
            approve_request.approver
            for approve_request in self.requests.filter(priority__gt=self.main_priority).select_related('approver')
        ]

    def get_emailed_approvers(self):
        return [
            approve_request.approver
            for approve_request in self.requests.filter(priority=self.main_priority).select_related('approver')
        ]
