# -*- coding: utf-8 -*-
"""
Created on Feb 7, 2014

@author: noob
"""
from .base import Api
from common.models import Component, KPI
from django.http import Http404
import logging
import json


class RegressAddKPI(Api):
    http_method_names = ['post']

    @staticmethod
    def post(request):
        post_params = request.body
        post_params = json.loads(post_params)
        try:
            component_obj = Component.objects.get(n=int(post_params['component']))
        except Exception:
            logging.exception('Component object was not found for number %s', post_params.get('component', None))
            raise Http404('Component not found')
        try:
            kpi_type = post_params['kpitype']
            kpi_params = post_params['params']
        except Exception as exc:
            logging.exception('Wrong body structure')
            return [{'success': 0, 'error': exc.__class__.__name__}]
        try:
            if kpi_type not in KPI.kpitype_map:
                kpi_type = dict(map(lambda x: (x[1], x[0]), KPI.kpicode_map.items())).get(int(kpi_type))
            kpi_dsc = f'{KPI.kpitype_map[kpi_type]};'
        except (ValueError, KeyError):
            return [{'success': 0, 'error': 'invalid kpi_type'}]

        kpi_essential = post_params.get('essential', 0)

        for key, value in kpi_params.items():
            if key == 'target' and value:
                kpi_dsc += 'Мишень "' + value.host + '"; '
            elif key == 'metric' and value:
                kpi_dsc += 'Метрика "' + value.code + '"; '
            elif key == 'case' and value:
                kpi_dsc += 'Гильза "' + str(value) + '"; '
            elif key == 'graphs' and value:
                kpi_dsc += ', '.join([str(item) for item in value]) + '; '

        if 'sla' not in kpi_params:
            kpi_params['sla'] = {}

        try:
            KPI.objects.create(
                ktype=kpi_type,
                component_id=component_obj.n,
                params_json=json.dumps(kpi_params),
                dsc=kpi_dsc,
                essential=kpi_essential,
            )
            return [{'success': 1}]
        except Exception as exc:
            logging.exception('Error during creating the KPI object')
            return [{'success': 0, 'error': exc.__class__.__name__}]
