# coding: utf-8


import logging

from idm.celery_app import app
from idm.core.models import System
from idm.framework.task import BaseTask
from idm.users.models import User
from idm.utils.tasks import get_object_or_fail_task, get_object_or_retry_task

log = logging.getLogger(__name__)


class SystemShutdown(BaseTask):
    monitor_success = False  # таски этого типа запускаются ad-hoc

    def init(self, system_pk, requester_pk):
        system = get_object_or_fail_task(System, pk=system_pk)
        requester = get_object_or_retry_task(User, pk=requester_pk)
        log.info('Try shutdown system %s and deprive or decline all roles', system.slug)
        try:
            system.shutdown(requester)
            log.info('System `%s` shutdown was successful', system.slug)
        except Exception:
            log.exception('System `%s` shutdown failed', system.slug)


SystemShutdown = app.register_task(SystemShutdown())
