# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2021  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.core.management.base import BaseCommand, CommandError
from django.db import connection, transaction
from django.utils import timezone

from passerelle.base.models import Job


class Command(BaseCommand):
    '''Run a job (internal command)'''

    def add_arguments(self, parser):
        parser.add_argument('--job-id', action='store', required=True)

    def handle(self, *args, **options):
        skip_locked = {'skip_locked': True}
        if not connection.features.has_select_for_update_skip_locked:
            skip_locked = {}
        with transaction.atomic():
            try:
                job = Job.objects.select_for_update(**skip_locked).get(pk=options['job_id'])
            except Job.DoesNotExist:
                raise CommandError('missing job')

            if job.status != 'registered':
                raise CommandError('cannot run job, status is %s' % job.status)
            if job.after_timestamp and job.after_timestamp >= timezone.now():
                raise CommandError('cannot run job, should be run after %s' % job.after_timestamp)

            job.status = 'running'
            job.save()
            # release lock
        job.run()
