from datetime import datetime, timedelta
from logging import Logger
from typing import List

from production.box._OrderChangerProductionBox import OrderChangerProductionBox
from production.command import (
    ProductionCommandProcessor,
    PurgeOrdersCommand,
)
from production.model import ProductionOrder


class RemoveReprocessedOrdersBox(OrderChangerProductionBox):
    def __init__(
        self,
        name,                       # type: str
        sons,                       # type: List[str]
        command_processor,          # type: ProductionCommandProcessor
        reprocessed_time_limit,     # type: int
        logger=None,                # type: Logger
    ):
        # type: (...) -> None

        super(RemoveReprocessedOrdersBox, self).__init__(name, sons, logger)
        self.command_processor = command_processor
        self.reprocessed_time_limit = int(reprocessed_time_limit)
        self.logger = logger

    def change_order(self, order):
        if order.first_processing and not order.purged:
            order_creation_time = datetime.strptime(order.created_at[0:19], "%Y-%m-%dT%H:%M:%S")
            if (datetime.now() - order_creation_time) > timedelta(seconds=self.reprocessed_time_limit):
                self.logger.error("Order removed after reprocessing time limit. Order: \n{}".format(str(order)))
                self._purge_order(order=order)
                return None

        return order

    def _purge_order(
        self,
        order,  # type: ProductionOrder
    ):
        # type: (...) -> None

        self.command_processor.handle_purge_orders_command(command=PurgeOrdersCommand([order.order_id]))
