import logging
import signal

from django.conf import settings
from django.core.management.base import BaseCommand

from jobs.worker import JobWorkerRunner

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = "Run the configured threaded job worker."

    def handle(self, *args, **options):
        log_level = getattr(logging, settings.JOB_WORKER_LOG_LEVEL, logging.INFO)
        logging.basicConfig(
            level=log_level,
            format="%(asctime)s %(levelname)s %(threadName)s %(name)s %(message)s",
            force=True,
        )
        runner = JobWorkerRunner()
        signal.signal(signal.SIGINT, runner.request_stop)
        signal.signal(signal.SIGTERM, runner.request_stop)
        self.stdout.write(
            self.style.SUCCESS(
                f"Starting {runner.thread_count} job worker thread(s) with log level {settings.JOB_WORKER_LOG_LEVEL}."
            )
        )
        runner.run_forever()
        self.stdout.write(self.style.SUCCESS("Job worker stopped."))
