from .base import ApiJob
from common.models import UploadToken, Job
from common.util.decorators import api_token_required, approve_required
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponseBadRequest, HttpResponse
import datetime
import logging
import json


@login_required
@approve_required
def jobclose_frontend(request):
    job_n = request.GET.get('job_n')
    user = request.user
    try:
        assert job_n, 'job_n required'
        job = Job.check_job(Job.objects.get(n=job_n))
        assert job.user == user, 'This is not your job!'

    except AssertionError as e:
        return HttpResponseBadRequest(e.message)
    except Job.DoesNotExist:
        return HttpResponseBadRequest('invalid job_n')
    except Job.Deleted:
        return HttpResponse(json.dumps([{'success': 0, 'msg': 'Job had been deleted'}]), content_type='application/json')

    if not job.td:
        job.td = datetime.datetime.now()
        try:  # tmp
            UploadToken.objects.filter(job=job.n).delete()
        except:
            pass
        job.quit_status = 8  # interrupted_stop_via_web
        job.save()
    return HttpResponse('')


class JobClose(ApiJob):
    http_method_names = ['get']

    @api_token_required
    def get(self, request, job):

        try:
            if not isinstance(request.user, AnonymousUser):
                user = request.user
                logging.error('Job %s was KILLED by %s', job.n, user.username)
        except:
            logging.exception('')

        now = datetime.datetime.now()
        if job.td:
            return [{'success': 0}]

        code = request.GET.get('exitcode', -1)
        if code not in (-1, 'None', '-1'):
            job.quit_status = code
        else:
            job.quit_status = 1
        job.td = now

        try:  # tmp
            UploadToken.objects.filter(job=job.n).delete()
        except:
            pass

        job.save()

        return [{'success': 1}]
