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


import logging

from idm.core.management.base import IdmBaseCommand
from idm.core.models import RoleNode
from idm.utils.lock import lock

log = logging.getLogger(__name__)


class Command(IdmBaseCommand):
    help = """Запускаем процедуру удаления подвисших ролей у удалённых узлов"""

    USE_LOCK = False

    STAGES_METHODS = [
        ('poke_deprived_with_returnable_roles', 'poke_hanging_deprived_nodes_with_returnable_roles'),
    ]
    STAGES = [pair[0] for pair in STAGES_METHODS]
    STAGES_DICT = dict(STAGES_METHODS)

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--stage', action='store', dest='stage', choices=self.STAGES
        )
        parser.add_argument(
            '--system', action='store', dest='system', type='system', required=False
        )

    def idm_handle(self, *args, **options):
        system = options.get('system')
        stage = options.get('stage')
        if stage is None:
            stages = self.STAGES
        else:
            stages = (stage,)

        system_comment = (' (for system %s)' % system.slug) if system else ''

        for stage in stages:
            with lock(self.lock_name, block=options['use_block_lock']) as locked:
                if not locked:
                    log.info('Stage: %s %s has not started', stage, system_comment)
                    return
                method = getattr(RoleNode.objects, self.STAGES_DICT[stage])
                try:
                    log.info('Poking hanging nodes %s. Stage: %s', system_comment, stage)
                    method(system=system)
                    log.info('Poked hanging nodes %s. Stage: %s', system_comment, stage)
                except Exception:
                    log.exception('Error while poking hanging nodes %s. Stage: %s', system_comment, stage)
