"""
Created on Jul 26, 2016

Tank BDK support
@author: noob
"""

from ..models import JobTank
from common.models import Server, Job, UploadToken
# from common.views import cache_lock
from django.http import HttpResponseBadRequest, HttpResponse, \
    HttpResponseNotFound, HttpResponseServerError
from json import dumps
import logging
import uuid


# @cache_lock
def claim_job(request):
    """
    Associates a job with a tank, that is allowed to claim it
    Returns Job number, it's config and UploadToken
    :param request: HTTP request
    """
    try:
        tank = request.GET.get('tank', '')
        assert tank
        server = Server.objects.get_or_create(host=tank)[0]
        tasks = JobTank.objects.filter(tank=server)
        jobs_available = Job.objects.filter(n__in=[t.job_id for t in tasks], tank=None, td=None, status='queued')
        job = jobs_available[0]
        job.tank = server
        job.status = 'claimed'
        job.save()
        logging.error('Tank {} claimed job # {}'.format(tank, job.n))

        upload_token = UploadToken.objects.get_or_create(job=job.n)
        if upload_token[1]:  # just created a new one
            upload_token[0].token = uuid.uuid4().hex
            upload_token[0].save()

        return HttpResponse(
            dumps({'success': True, 'error': '', 'job': {'id': job.id,
                                                         'upload_token': upload_token[0].token,
                                                         'config': job.configinitial}
                   }),
            content_type='application/json')
    except AssertionError:
        return HttpResponseBadRequest(dumps({'success': False, 'error': 'Unknown tank'}),
                                      content_type='application/json')
    except IndexError:
        logging.debug('No jobs found for tank %s', request.GET.get('tank', ''))
        return HttpResponseNotFound(dumps({'success': False, 'error': 'No jobs for you'}),
                                    content_type='application/json')
    except Exception as exc:
        logging.warning('Problems with claim job', exc_info=True)
        return HttpResponseServerError(dumps({'success': False, 'error': exc}), content_type='application/json')
