# -*- coding: utf-8 -*-
from common.util.clients import CacheClient
from .base import ApiJob
from common.models import UploadToken, Job
from django.http import HttpResponseBadRequest, HttpResponse
from django_yauth.decorators import yalogin_required
from django_yauth.user import AnonymousYandexUser
import datetime
import logging
import subprocess
from settings import BASE_DIR


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

    def get(self, request, job):
        try:
            if not isinstance(request.yauser, AnonymousYandexUser):
                user = request.yauser
                logging.error('Job {} was KILLED by {}'.format(job.n, user.login))
        except Exception:
            logging.warning('Failed to detect user when closing job %s', job.n, exc_info=True)

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

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

        try:  # tmp
            UploadToken.objects.filter(job=job.n).delete()
        except Exception:
            logging.debug('Failed to delete upload token for job %s', job.n)

        job.save()
        cache = CacheClient()
        cache.delete('job_{}_td'.format(job.n))

        # self.precise_quantiles(request, job)

        subprocess.Popen(
            [BASE_DIR + '/www/manage.py', 'aggregate', str(job.n)],
            stdout=subprocess.PIPE, stderr=subprocess.STDOUT
        )

        return [{'success': 1}]


@yalogin_required
def jobclose_frontend(request):
    """
    frontend handler
    :param request:
    """

    job_n = request.GET.get('job_n')
    try:
        assert job_n
    except AssertionError:
        return HttpResponseBadRequest('job_n required')
    job = Job.objects.get(n=job_n)
    if not job.td:
        job.td = datetime.datetime.now()
        UploadToken.objects.filter(job=job.n).delete()
        job.quit_status = 8  # interrupted_stop_via_web
        job.save()
        logging.debug('[job close] Job %s closed via frontend', job.n)
        cache = CacheClient()
        cache.delete('job_{}_td'.format(job.n))
    return HttpResponse('')
