import sys
import traceback

import structlog
from django.core.management.base import BaseCommand
from django.utils import timezone

from vbv_lernwelt.core.models import JobLog

logger = structlog.get_logger(__name__)


# pylint: disable=abstract-method
class LoggedCommand(BaseCommand):
    def execute(self, *args, **options):
        name = getattr(self, "name", "")
        if not name:
            name = sys.argv[1]

        logger.info("start LoggedCommand", job_name=name, label="job_log")

        self.job_log = JobLog.objects.create(job_name=name)
        try:
            super(LoggedCommand, self).execute(*args, **options)
            self.job_log.refresh_from_db()
            self.job_log.ended = timezone.now()
            self.job_log.success = True
            self.job_log.save()
            logger.info(
                "LoggedCommand successfully ended", job_name=name, label="job_log"
            )
        except Exception as e:
            self.job_log.refresh_from_db()
            self.job_log.error_message = str(e)
            self.job_log.stack_trace = traceback.format_exc()
            self.job_log.save()
            logger.error("LoggedCommand failed", job_name=name, label="job_log")
            raise e
