import iso8601
from _StatisticBox import StatisticBox
from production.model import ProductionOrder
from typing import List, Any


class TimeThresholdStatisticBox(StatisticBox):
    def __init__(self, name, sons, publish_scheduler, logger, get_config):
        super(TimeThresholdStatisticBox, self).__init__(
            name,
            sons,
            publish_scheduler,
            logger,
            get_config
        )

        self.mode = get_config("Mode")
        self.type = get_config("ValueType") or "PERCENTAGE"
        self.threshold = int(get_config("Threshold"))

    def get_order_value(self, order):
        # type: (ProductionOrder) -> Any

        start_tag = self.get_tag_with_sub_order_id(order, self.start_tag)
        start_time = iso8601.parse_date(order.tags[start_tag])

        end_tag = self.get_tag_with_sub_order_id(order, self.end_tag)
        end_time = iso8601.parse_date(order.tags[end_tag])

        tag_interval = (end_time - start_time).total_seconds()
        return self.is_order_in_threshold(tag_interval)

    def update_statistics(self, values):
        # type: (List[bool]) -> float

        in_threshold = len([x for x in values if x is True])
        if self.type == "PERCENTAGE":
            return 100 * (float(in_threshold) / (len(values) or 1))

        return in_threshold

    def is_order_in_threshold(self, tag_time):
        return tag_time < self.threshold if self.mode == "UNDER" else tag_time > self.threshold
