from django.db import models

from idm.core.constants.action import ACTION


class BaseAction(models.Model):
    class Meta:
        abstract = True

    @property
    def comment(self):
        comment = None
        if self.data and isinstance(self.data, dict):
            comment = self.data.get('comment')
            if self.transfer_id and self.role_id is not None:
                self.fetch_transfer()
                comment += self.transfer.as_comment(kept_granted=self.action == 'keep_granted')
        return comment

    def as_verb(self):
        """Хьюманизирует действие пользователя в зависимисти от его пола в виде глагола"""
        is_female = False
        if self.impersonator is not None:
            is_female = self.impersonator.is_female()
        elif self.requester is not None:
            is_female = self.requester.is_female()
        return ACTION.ACTIONS[self.action][is_female]

    def as_noun(self):
        """Хьюманизирует действие пользователя как существительное"""
        return ACTION.ACTIONS[self.action][2]

    def __str__(self):
        result = [f'{self.__class__.__name__}={self.action}', f'added={self.added}']
        if self.user_id:
            result.append('user=%s' % self.user.username)
        if self.group_id:
            result.append('group=%s[%s]' % (self.group.slug, self.group.type))
        if self.system:
            result.append('system=%s' % self.system.slug)
        if self.data:
            if 'comment' in self.data:
                result.append('comment=%s' % self.comment)
            data = {key: value for key, value in self.data.items() if key != 'comment'}
            if data:
                result.append('data=%s' % data)
        return ' '.join(result)