#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from django.core.management.base import BaseCommand

from common.models import Job
from common.util.job_trail import set_job_trail


class Command(BaseCommand):
    help = 'Sets job_trail for the finished jobs for the last half-hour'

    def add_arguments(self, parser):
        parser.add_argument('job_id', type=int)

    def handle(self, *args, **options):
        job = Job.objects.filter(n=options['job_id'])
        if job:
            job = job[0]
            set_job_trail(job)
            try:
                job.finalized = True
                job.save()
                logging.debug('[aggregate] Job %s finalized and saved', job.n)
            except Exception:
                logging.error('[aggregate] Failed to finalize job %s', job.n)

