#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import logging
from infra.yasm.yasmapi import GolovanRequest


def calculate(signal, host, params, end_time, interval):
    logging.basicConfig()
    period = 5  # point per 5 seconds
    assert interval / period >= 5  # at least 3 points to calculate result (min/max points would be dropped)
    num_of_points = interval / period
    start_time = end_time - period * num_of_points  # seconds
    signals = [params + 'host=' + host + ':' + signal]
    max_retry = 5
    retry_delay = 5  # seconds, should be at least >2, to avoid 429 from Golovan server

    min_value = 1234567890
    max_value = -1
    sum_total = 0
    counter = 0

    for timestamp, values in GolovanRequest(host, period, start_time, end_time, signals, max_retry, retry_delay):
        assert timestamp
        assert values
        for i in values.values():
            counter += 1
            if i > max_value:
                max_value = i
            if i < min_value:
                min_value = i
            sum_total += i

    assert (counter > 2)
    sum_total -= (min_value + max_value)
    avg = float(sum_total) / (counter - 2)

    return avg
