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


import logging

from django.conf import settings
from django.utils.translation import ugettext as _

from idm.core.management.base import IdmBaseCommand
from idm.core.models import Role
from idm.notification.utils import send_notification

log = logging.getLogger(__name__)


class Command(IdmBaseCommand):
    help = 'Находит странные роли, у которых состояние granted, но при этом существуют невыполненные запросы.'

    def idm_handle(self, *args, **options):
        try:
            log.info('getting strange roles from db')
            roles = Role.objects.filter(state='granted', requests__is_done=False).values_list('pk').distinct()
            roles = Role.objects.filter(pk__in=roles).select_related('user', 'system', 'node')
            count = roles.count()
            log.info('got %s strange roles from db' % count)
            if count > 0:
                log.info('sending a message about strange roles')
                send_notification(
                    subject=_('Странные роли.'),
                    message_templates='emails/service/role_with_broken_request.txt',
                    recipients=settings.EMAILS_FOR_REPORTS,
                    context=dict(roles=roles),
                )
        except Exception:
            log.exception('error during command execution')
            raise
