"""
Created on Aug 10, 2016

@author: noob
"""

from .base import ApiJob
from django.http import HttpResponse
import logging
import json


class JobConfigInitial(ApiJob):
    http_method_names = ['post', 'get']

    @staticmethod
    def get(_, job):
        """

        :param _: HTTP request
        :param job: Job OBJECT
        """
        configinitial = ''
        try:
            configinitial = job.configinitial
        except:
            logging.exception('Could not get configinitial for job {} due to:'.format(job.n))
        return HttpResponse(configinitial, content_type='text/plain; charset=UTF-8')

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

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