#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Jan 31, 2017

@author: noob
"""

from .base import ApiMobileJob
from mobilepage.models import MobileComponent, MobileJob
from django.http import HttpResponseBadRequest, HttpResponseServerError, \
    HttpResponse
from django_yauth.decorators import yalogin_required
from json import dumps
from simplejson import loads
import logging


class MobileJobMetaInfo(ApiMobileJob):
    """
    job edit
    """
    http_method_names = ['post']

    @staticmethod
    def post(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(dumps('Params not set!'), content_type='application/json')

        params = loads(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'}

        set_smth = 0
        for name, val in params_d.items():
            if name in params:
                set_smth = 1
                new_val = params[name]
                if name in ('task', 'name') and new_val:
                    new_val = new_val[0:120]
                elif name == 'component':
                    if new_val and new_val.isdigit():  # numeric
                        try:
                            component_obj = MobileComponent.objects.get(
                                n=int(new_val),
                            )
                            new_val = component_obj.n
                        except MobileComponent.DoesNotExist:  # we don't need new numeric components
                            logging.error('Digital component for job {}!'.format(job.n))
                            return HttpResponseBadRequest(dumps('Digital component!'), content_type='application/json')
                    elif new_val and not new_val.isdigit():  # not numeric
                        component_obj, _ = MobileComponent.objects.get_or_create(
                            name=new_val,
                            tag=job.task.project,
                        )
                        new_val = component_obj.n
                    else:  # no component
                        new_val = 0
                setattr(job, val, new_val)

        if set_smth:
            try:  # save what was changed
                job.save()
            except:
                logging.exception("Failed to edit job")
                return HttpResponseServerError(dumps('Can not edit job!'), content_type='application/json')  # !!!

        return [{'success': 1}]


@yalogin_required
def jobedit_frontend(request):
    """
    frontend handler
    :param request:
    """

    job_n = request.GET.get('job_n')
    try:
        assert job_n
    except AssertionError:
        return HttpResponseBadRequest('job_n required')

    params = request.POST
    job = MobileJob.objects.get(n=job_n)
    success = update_job_metainfo(job, params)

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


def update_job_metainfo(job, params):
    """
    for frontend handler
    :param job:
    :param 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.items():
        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
