import math

from ressources.acced.production.acced_production_service import CONTRAT_DOSE_PILLBOX, \
    CONTRAT_CADENCE_DOSE_PILLBOX, CONTRAT_CADENCE_PILLBOX, _get_config, State


def get_pillbox_mean(counter_values):
    threshold_dose = _get_config(property=CONTRAT_DOSE_PILLBOX)
    threshold_cadence_dose = _get_config(property=CONTRAT_CADENCE_DOSE_PILLBOX)
    threshold_cadence = _get_config(property=CONTRAT_CADENCE_PILLBOX)

    pillbox_num = sum(filter(lambda s: s > 0,
                             map(lambda d: d['pillbox_num'], counter_values)))
    pillbox_dose_num = sum(filter(lambda s: s > 0,
                                  map(lambda d: d['pillbox_dose_num'], counter_values)))
    picking_pillbox_time = sum(filter(lambda s: s > 0,
                                      map(lambda d: d['picking_pillbox_time'], counter_values)))

    dose_per_pillbox = round(pillbox_dose_num / pillbox_num, 2) if pillbox_num > 0 else None
    pillbox_per_hour = round(pillbox_num / picking_pillbox_time, 2) if picking_pillbox_time > 0 else 0
    dose_per_hour = round(pillbox_dose_num / picking_pillbox_time, 2) if picking_pillbox_time > 0 else 0

    pillbox_state = State.UNKNOW.value if dose_per_pillbox is None or math.isnan(dose_per_pillbox) else State.KO.value

    if pillbox_state is not State.UNKNOW.value:
        if (dose_per_pillbox > threshold_dose and dose_per_hour >= threshold_cadence_dose) or \
           (dose_per_pillbox <= threshold_dose and pillbox_per_hour >= threshold_cadence):
            pillbox_state = State.OK.value
        elif (dose_per_pillbox > threshold_dose and dose_per_hour >= (0.9 * threshold_cadence_dose)) or \
             (dose_per_pillbox <= threshold_dose and pillbox_per_hour >= (0.9 * threshold_cadence)):
            pillbox_state = State.WARNING.value

    return {
        'unit': 'unit.dose.h' if dose_per_pillbox > threshold_dose else 'unit.pillbox.h',
        'mean': dose_per_hour if dose_per_pillbox > threshold_dose else pillbox_per_hour,
        'cadence_doses': dose_per_pillbox,  # dose per pillbox
        'cadence_hour': pillbox_per_hour,  # pillbox per hour
        'dose_hour': dose_per_hour,  # dose per hour
        'state': pillbox_state,
        'threshold': {
            'min': threshold_cadence_dose if dose_per_pillbox > threshold_dose else threshold_cadence,
            'warning': round(threshold_cadence_dose * 0.9, 2)
            if dose_per_pillbox > threshold_dose
            else round(threshold_cadence * 0.9, 2),
            'unit': 'unit.dose.h' if dose_per_pillbox > threshold_dose else 'unit.pillbox.h',
        }
    } if pillbox_state != State.UNKNOW.value else None
