import logging

import yenv

from staff.celery_app import app
from staff.lib.tasks import LockedTask
from staff.person.passport.internal import IntPassport
from staff.person.models import PersonBlockActions

logger = logging.getLogger(__name__)


@app.task(ignore_result=True)
class BlockPassport(LockedTask):
    def _try_block(self, unblocked_person):
        person = unblocked_person.person
        try:
            logger.info('Blocking %s', person.login)
            passport = IntPassport(person.uid)
            passport.block()

        except Exception as e:
            logger.error('Failed to block %s', person.login)
            unblocked_person.passport_block_last_action_reason = str(e)
            return

        unblocked_person.is_passport_blocked = True
        unblocked_person.passport_block_last_action_reason = None
        unblocked_person.save()
        logger.info('Passport for %s blocked', person.login)

    def locked_run(self, *args, **kwargs):
        if yenv.type != 'production':
            logger.info('Do not block passport since we aren\'t in production')
            return

        unblocked_persons = PersonBlockActions.objects.filter(is_passport_blocked=False)

        for unblocked_person in unblocked_persons:
            self._try_block(unblocked_person)
