from collections import OrderedDict

from common.models import Server
from common.util.aggregators import MonitoringAggregator
from monitoring.models import Metric
from .base import ApiJob


def round_or_none(value, base=3):
    return round(value, base) if value is not None else None


class JobMonitoring(ApiJob):
    """
    job_obj monitoring data
    """

    @staticmethod
    def get(request, job):
        """
        :param request: HTTP request
        :param job: job OBJECT passed from request
        """

        dt_from = request.GET.get('from') or request.GET.get('start')
        dt_to = request.GET.get('to') or request.GET.get('end')
        res = []
        aggregator = MonitoringAggregator(job, start=dt_from, end=dt_to)
        arr = aggregator.get_raw_data()
        for a in arr:
            server = Server.objects.get_or_create(host=a[0])[0]
            metric = Metric.objects.get_or_create(code=a[1])[0]
            res.append(OrderedDict([
                        ('host', server.host),
                        ('metric', metric.code),
                        ('avg', round_or_none(a[2])),
                        ('stddev', round_or_none(a[3])),
                        ('min', round_or_none(a[4])),
                        ('max', round_or_none(a[5])),
                        ('median', round_or_none(a[6])),
                     ]))
        res = sorted(res, key=lambda x: str(x['host']) + str(x['metric']))
        return res
