"""
Created on Aug 26, 2016

@author: noob
"""

from common.util.decorators import api_token_required
from api.views.base import ApiJob
import logging
from json import loads, dumps
from django.http import HttpResponseBadRequest
from common.models import JobImbalance


class JobSetImbalance(ApiJob):
    """
    job edit
    """
    http_method_names = ['post']

    @api_token_required
    def post(self, request, job):
        """
        :param request: HTTP request
        :param job: job object passed from request
        """
        try:
            params = request.body  # POST.get('params')
            
            if not params:
                logging.error("Params not set")
                return HttpResponseBadRequest(dumps('Params not set!'), content_type='application/json')
            
            params = loads(params)
            logging.info("Post parameters passed are: %s", params)
            logging.error('DDDD %s', params)
            imb_val = params.get('imbalance', '')
            if imb_val != '':
                if isinstance(imb_val, int):
                    imb = job.jobimbalance_set.all()
                    if imb:
                        imb = imb[0]
                    else:
                        imb = JobImbalance(up=job)
                    person = params.get('person', '')
                    if person:
                        imb.user = person
                    imb.hum_processed = 1
                    if imb_val != -1:
                        imb.hum_isimbalance = 1
                        imb.hum_imbalance = imb_val
                    else:
                        imb.hum_isimbalance = 0
                    imb.save()
                    # update job_imbalance
                    # set user='$user', hum_processed=1, hum_isimbalance=$is_imb, hum_imbalance=$user_imb
                    # where up=$job
                else:
                    logging.exception("Imbalance is not numeric: %s", imb_val)
            
            new_dsc = params.get('description', '')
            if new_dsc:
                job.dsc += '\n%s' % new_dsc
                job.save()
            return [{'success': True}]
        except:
            logging.exception('')
            return [{'success': False}]
