"""
Created on Jul 3, 2013

@author: noob
"""

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


@login_required
@approve_required
def job_configinfo(request):
    """
    :param request: HTTP request
    """
    job_n = request.GET.get('job_n')
    try:
        assert job_n
    except AssertionError:
        return HttpResponseBadRequest('job_n required')

    try:
        job = Job.check_job(Job.objects.get(n=job_n))
    except Job.Deleted:
        return HttpResponse(json.dumps([{'success': 0, 'msg': 'Job had been deleted'}]), content_type='application/json')
    except Job.DoesNotExist:
        raise Http404('Job not found')

    try:    
        assert request.user == job.user
        configinfo = job.configinfo   
    except AssertionError:
        configinfo = ''
        logging.error('Wrong job owner')
    except:
        configinfo = ''
        logging.exception('Could not get configinfo for job %s due to:', job.n)
    return HttpResponse(configinfo, content_type='text/plain; charset=UTF-8')


class JobConfigInfo(ApiJob):
    http_method_names = ['post']

    @api_token_required
    def post(self, request, job, **kwargs):
        """

        :param request: HTTP request
        :param job: Job OBJECT
        """
        try:
            configinfo = request.POST.__getitem__('configinfo')
        except KeyError:
            error = 'No "configinfo" parameter passed in post request for job %s' % job.n
            logging.error(error)
            return HttpResponse(json.dumps([{'success': 0, 'error': error}]), content_type='application/json')
        except Exception, exc:
            logging.exception('Could not retrieve "configinfo" parameter from post request for job %s due to:', job.n)
            return HttpResponse(json.dumps([{'success': 0, 'error': str(exc.__class__.__name__)}]),
                                content_type='application/json')
        try:
            job.configinfo = configinfo
            job.save()
            logging.info('Set configinfo for job %s', job.n)
            return HttpResponse(json.dumps([{'success': 1}]), content_type='application/json')
        except Exception, exc:
            logging.exception("Could not set configinfo for job %s due to:", job.n)
            return HttpResponse(json.dumps([{'success': 0, 'error': exc.__class__.__name__}]),
                                content_type='application/json')
