# coding: utf-8
import logging

from idm.core.management.base import IdmBaseCommand
from idm.core.models import Role
from idm.monitorings.metric import ActiveRolesOfInactiveGroupsMetric
from idm.utils.replication import use_slave

log = logging.getLogger(__name__)


class Command(IdmBaseCommand):
    """
    https://st.yandex-team.ru/IDM-3589

    """

    help = 'Проверяем неактивные группы с активными ролями'

    @use_slave()
    def idm_handle(self, *args, **options):
        log.info('Check granted roles from deprived groups')

        group_roles_qs = Role.objects.of_inactive_groups()
        personal_roles_qs = Role.objects.children_of_inactive_groups()
        personal_by_ref = Role.objects.children_of_inactive_refs()

        group_roles_amount = group_roles_qs.returnable().exclude(state='onhold')
        personal_roles_amount = personal_roles_qs.returnable().exclude(state='onhold')
        group_roles_onhold_amount = group_roles_qs.onhold()
        personal_roles_onhold_amount = personal_roles_qs.onhold()
        personal_by_ref_amount = personal_by_ref.returnable()

        result = {
            'group_roles_amount': group_roles_amount.count(),
            'personal_roles_amount': personal_roles_amount.count(),
            'group_roles_onhold_amount': group_roles_onhold_amount.count(),
            'personal_roles_onhold_amount': personal_roles_onhold_amount.count(),
            'personal_by_ref_amount': personal_by_ref_amount.count(),
        }

        if any(result.values()):
            log.warning('Found %s roles from deprived groups and %s ref roles', group_roles_amount, personal_roles_amount)

        ActiveRolesOfInactiveGroupsMetric.set(result)
        log.info('Finish checking granted roles from deprived groups')
