"""
Created on Dec 6, 2013

@author: noob
"""

from .base import Api
from collections import OrderedDict
from common.models import Component, KPI
from django.http import Http404
import logging
from copy import deepcopy


class RegressKPIList(Api):
    @staticmethod
    def get(request, *args):

        try:
            component_obj = Component.objects.get(n=int(args[0]))
        except:
            logging.exception('')
            raise Http404('Component not found')
        try:
            kpis = KPI.objects.filter(component_id=component_obj.n)
            if request.GET.get('essential', ''):
                kpis = kpis.filter(essential=True)
            kpis = kpis.order_by('ktype')
        except KPI.DoesNotExist:
            raise Http404('Component KPIs not found')

        res = []

        for kpi in kpis:
            try:
                if kpi.ktype.startswith('monitoring__'):
                    params = deepcopy(kpi.params)
                    if params.get('metric', ''):
                        params['metric'] = params['metric'].id
                    if params.get('target', ''):
                        params['target'] = params['target'].n
                else:
                    params = kpi.params
                res.append(OrderedDict((
                    ('n', kpi.n),
                    ('kpitype', kpi.ktype),
                    ('essential', kpi.essential),
                    ('params', params),
                    ('dsc', kpi.dsc)
                )))
            except:
                logging.exception('')

        return res
