# -*- coding: utf-8 -*-
"""
Created on May 31, 2022

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


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

    @staticmethod
    def post(request):

        post_params = json.loads(request.body)

        try:
            component = int(post_params['component'])
            kpi_n = int(post_params['n'])
            kpi_essential = post_params.get('essential', 0)
            kpi_params = post_params['params']
            kpi_type = post_params['kpitype']
            kpi_dsc = post_params.get('dsc', '')
        except (KeyError, TypeError) as exc:
            logging.exception('Post body is incomplete')
            return [{'success': 0, 'error': exc.__class__.__name__}]

        try:
            component_obj = Component.objects.get(n=component)
        except Component.DoesNotExist:
            logging.exception('Regression component %s not found', component)
            raise Http404('Component not found')

        try:
            kpi_obj = KPI.objects.get(n=kpi_n)
        except KPI.DoesNotExist:
            logging.exception('KPI number %s not found', kpi_n)
            raise Http404('KPI not found')

        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_name = f'{KPI.kpitype_map[kpi_type]};'
        except (ValueError, KeyError):
            return [{'success': 0, 'error': 'invalid kpi_type'}]

        if not kpi_dsc:
            kpi_dsc = kpi_name
            for key, value in kpi_params.items():
                if key == 'target' and value:
                    kpi_dsc += f'Мишень {value.host}; '
                if key == 'metric' and value:
                    kpi_dsc += f'Метрика {value.code}; '
                if key == 'case' and value:
                    kpi_dsc += f'Гильза {str(value)}; '

        kpi_params = check_kpi_params(kpi_params)

        try:
            kpi_obj.params_json = json.dumps(kpi_params)
            kpi_obj.essential = kpi_essential
            kpi_obj.dsc = kpi_dsc
            kpi_obj.save()
            return [{'success': 1}]
        except Exception as exc:
            logging.exception('Error during updating the KPI object')
            return [{'success': 0, 'error': exc.__class__.__name__}]


def check_kpi_params(kpi_params):
    if not isinstance(kpi_params, dict):
        raise Http404('Wrong KPI')
    kpi_params.setdefault('sla', {})
    kpi_params.setdefault('graphs', [])
    return kpi_params
