# -*- coding: utf-8 -*-
import logging

import waffle

from idm.core.constants.action import ACTION
from idm.core.management.base import IdmBaseCommand
from idm.core.models import Role, System


log = logging.getLogger(__name__)


class Command(IdmBaseCommand):
    help = 'Отзываем роли в выключенных системах'

    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,
        )

    @staticmethod
    def process_one_system(system):
        log.info('Try deprive and decline roles in inactive system `%s`', system.slug)
        try:
            system.shutdown(requester=None, action=ACTION.MASS_ACTION)
        except Exception:
            log.exception('Can\'t deprive and decline roles in inactive system `%s`', system.slug)

    def process_all_systems(self):
        systems_ids = set(
            Role.objects
            .returnable()
            .filter(system__is_active=False)
            .values_list('system_id', flat=True)
        )
        systems = System.objects.filter(id__in=systems_ids)
        for system in systems:
            self.process_one_system(system)

    def idm_handle(self, *args, **options):
        if not (options.get('force') or waffle.switch_is_active('idm.regular_deprive_roles_in_inactive_systems')):
            log.info('Flag `idm.regular_deprive_roles_in_inactive_systems` is inactive')
            return
        log.info('Start regular process from deprive roles in inactive systems')
        system = options.get('system')
        if system:
            self.process_one_system(system)
        else:
            self.process_all_systems()
        log.info('Complete regular process from deprive roles in inactive systems')
