import logging
import math

from ressources.acced.production.acced_production_service import CONTRAT_AVALABILITY_PERCENTAGE, _get_config, State

logger = logging.getLogger('median.webserver')


def get_availability_mean(counter_values):
    time_defect_resolve = sum(list(filter(lambda s: s > 0,
                              map(lambda d:  d['time_defect_resolve'], counter_values))))
    time_working = sum(list(filter(lambda s: s > 0,
                            map(lambda d: d['time_working'], counter_values))))

    mean = round((1 - (time_defect_resolve / time_working))*100, 2) if time_working > 0 else None

    state = State.UNKNOW.value if mean is None or math.isnan(mean) else State.KO.value
    threshold = _get_config(property=CONTRAT_AVALABILITY_PERCENTAGE)

    if state != State.UNKNOW.value:
        if mean >= threshold:
            state = State.OK.value
        elif mean >= (0.9 * threshold):
            state = State.WARNING.value

    return {
        'mean': mean,
        'state': state,
        'threshold': {
            'min': threshold,
            'warning': round(0.9 * threshold, 2),
            'unit': 'unit.percentage'
        }
    } if state != State.UNKNOW.value else None
