#!/usr/bin/env python
# -*- coding: utf-8 -*-
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 HttpResponseBadRequest, HttpResponse
import json
import logging


@login_required
@approve_required
def jobedit_frontend(request):
    job_n = request.GET.get('job_n')
    user = request.user
    try:
        assert job_n, 'job_n required'
        job = Job.check_job(Job.objects.get(n=job_n))
        assert job.user == user, 'This is not your job!'
    except AssertionError as e:
        return HttpResponseBadRequest(e.message)
    except Job.DoesNotExist:
        return HttpResponseBadRequest('invalid job_n')
    except Job.Deleted:
        return HttpResponse(json.dumps([{'success': 0, 'msg': 'Job had been deleted'}]), content_type='application/json')

    params = request.POST

    success = update_job_metainfo(job, params)

    return HttpResponse(json.dumps({'success': success}))


class JobMetaInfo(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
        """
        params = request.body  # POST.get('params')

        if not params:
            logging.error("Params not set")
            return HttpResponseBadRequest(json.dumps('Params not set!'), content_type='application/json')

        params = json.loads(params)
        logging.info("Post parameters passed are: %s", params)

        success = update_job_metainfo(job, params)

        return [{'success': success}]


def update_job_metainfo(job, params):
    params_d = {
        'starred': 'flag',
        'description': 'dsc',
        'component': 'component',
        'loop': 'loop_cnt',
        'ammo': 'ammo_path',
        'version': 'ver',
        'tank_type': 'type',
        'instances': 'instances',
        'command_line': 'command_line',
        'name': 'name',
        'test_type': 'test_type'
    }

    set_smth = 0
    for name, val in params_d.iteritems():
        if name in params:
            set_smth = 1
            new_val = params[name]
            if name in ('version', 'name') and new_val:
                new_val = new_val[0:120]
            elif name == 'ammo' and new_val:
                new_val = new_val[0:256]
            elif name == 'command_line' and new_val:
                new_val = new_val[0:512]
            setattr(job, val, new_val)

    if set_smth:
        try:  # save what was changed
            job.save()
            return True
        except:
            logging.exception("Failed to edit job")
            return False
