import logging
from typing import Optional

import waffle

from idm.core import depriving
from idm.core.management.base import IdmBaseCommand
from idm.core.models import System
from idm.core.tasks.roles import DepriveDeprivingRoles, DeprivePersonalRolesOfDismissedUsers


log = logging.getLogger(__name__)


class Command(IdmBaseCommand):
    help = 'Отзываем роли в статусе depriving, если выполнены нужные условия.'

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--force',
            action='store_true',
            dest='force',
            default=False,
        )

        parser.add_argument(
            '--system',
            action='store',
            dest='system',
            type='system',
            required=False,
        )

    @classmethod
    def schedule_tasks_on_revoking_roles(cls, system: Optional[System] = None, force: bool = False):
        depriver_roles_ids = depriving.get_roles_ids_to_deprive(system=system, force=force)
        if not depriver_roles_ids:
            log.info('Command idm_deprive_depriving_roles did not find roles that meet deprive conditions')
            return

        for depriver, roles_ids in depriver_roles_ids.items():
            DepriveDeprivingRoles.delay(depriver_id=depriver, roles_ids=roles_ids)

    @classmethod
    def schedule_tasks_on_revoking_personal_roles_of_dismissed_users(cls, system: Optional[System]):
        system_id = system.id if system else None
        DeprivePersonalRolesOfDismissedUsers.delay(system_id=system_id)

    def idm_handle(self, *args, **options):
        log.info('Start deprive depriving roles')
        if not waffle.switch_is_active('idm.deprive_not_immediately'):
            log.warning("Waffle idm.deprive_not_immediately is inactive. Pass")
            return

        system = options.get('system')
        force = options.get('force', False)

        self.schedule_tasks_on_revoking_roles(system, force)
        self.schedule_tasks_on_revoking_personal_roles_of_dismissed_users(system)

        log.info('Deprive depriving roles completed')
