"""
Created on Jul 26, 2018

@author: noob
"""

from .base import ApiJob
from common.models import Job, JobMonitoringConfig
from django.http import HttpResponse, HttpResponseBadRequest
import json
import logging
from django_yauth.decorators import yalogin_required


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

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

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

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

        :param request: HTTP request
        :param job: Job OBJECT
        """
        try:
            monitoring_config = request.POST.__getitem__('monitoringconfig')
        except KeyError:
            error = 'No "monitoring_config" 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 "monitoring_config" 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:
            jmc = JobMonitoringConfig.objects.get_or_create(job=job)[0]
            jmc.contents = monitoring_config
            jmc.save()
            return HttpResponse(json.dumps([{'success': 1}]), content_type='application/json')
        except Exception as exc:
            logging.exception("Could not set monitoring_config for job {} due to:".format(job.n))
            return HttpResponse(json.dumps([{'success': 0, 'error': repr(exc)}]),
                                content_type='application/json')


@yalogin_required
def job_monitoring_config(request):
    """
    frontend handler
    :param request:HTTP 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)
    try:
        assert request.user == job.user, 'Wrong job owner'
        monitoring_config = JobMonitoringConfig.objects.filter(job=job)
        assert monitoring_config, 'No monitoring config for job {}'.format(job.n)
        monitoring_config = monitoring_config.contents
    except AssertionError as aexc:
        monitoring_config = ''
        logging.error(aexc)
    except:
        monitoring_config = ''
        logging.exception('Could not get monitoring config for job {} due to:'.format(job.n))
    return HttpResponse(monitoring_config, content_type='text/plain; charset=UTF-8')
