import logging
from optparse import make_option
from django.core.management.base import BaseCommand

from staff.monitorings.juggler import Juggler
from staff.monitorings.views.juggler import get_check_result


logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Send events to juggler'
    option_list = BaseCommand.option_list + (
        make_option(
            '--check',
            dest='check',
            help='Check ro send',
        ),
    )

    def handle(self, *args, **options):
        check_name: str = options.get('check')
        logger.info('Checking %s', check_name)
        try:
            self._run_check(check_name)
        except Exception:
            logger.exception('Check %s failed', check_name)
            raise
        logger.info('%s sent to Juggler', check_name)

    @staticmethod
    def _run_check(check_name: str):
        result, juggler_namespace = get_check_result(check_name)

        with Juggler(juggler_namespace) as juggler:
            juggler.process_check_result(service=check_name, check_result=result)
