from datetime import datetime

from production.model import ProdStates, ProductionOrder
from ._OrderChangerProductionBox import OrderChangerProductionBox


class ReprocessOrdersBox(OrderChangerProductionBox):
    def __init__(self, name, sons, publish_scheduler, reprocess_time=None, reprocess_display_time=None, logger=None):
        super(ReprocessOrdersBox, self).__init__(name, sons, logger)
        self.publish_scheduler = publish_scheduler
        self.reprocess_time = reprocess_time
        self.reprocess_display_time = reprocess_display_time if self.reprocess_time is None else None

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

        if order.prod_state != ProdStates.INVALID:
            if self.reprocess_time is not None:
                self.publish_scheduler.schedule_publish(order.order_id, self.reprocess_time)

            if self.reprocess_display_time is not None and order.display_time not in [None, "", " "]:
                display_time = datetime.strptime(order.display_time[0:19], "%Y-%m-%dT%H:%M:%S")
                current_time = datetime.now()

                seconds_to_reprocess = self.reprocess_display_time - (current_time - display_time).total_seconds()
                if seconds_to_reprocess < 0:
                    seconds_to_reprocess = 1
                self.publish_scheduler.schedule_publish(order.order_id, seconds_to_reprocess)

        return order
