from application.model import Configurations
from application.service import BenefitService
from application.service import OrderService


class OnOrderTotalInteractor(object):
    def __init__(self, configs, benefit_service, order_service):
        # type: (Configurations, BenefitService, OrderService) -> None

        self.configs = configs
        self.logger = configs.logger
        self.benefit_service = benefit_service
        self.order_service = order_service

    def execute(self, pos_id):
        # type: (int) -> None

        static_uow = self.benefit_service.get_static_unit_of_work(
            pos_id=pos_id,
            fill_table_info=True,
        )
        static_uow.pos_ot.blkopnotify = True

        updated_order_picture = self.benefit_service.apply_automatic_benefits_on_order(
            pos_id=pos_id,
            static_uow=static_uow,
            on_total=True,
        )

        order_picture = updated_order_picture if updated_order_picture is not None else static_uow.order_picture
        if order_picture.get("state") == "TOTALED":
            product_groups = self.benefit_service.product_groups
            order_picture = self.benefit_service.validate_benefits(
                pos_id=pos_id,
                static_uow=static_uow,
                product_groups=product_groups,
            )
            static_uow.set_order_picture(order_picture=order_picture)

            order_picture = self.benefit_service.remove_invalid_benefits(
                pos_id=pos_id,
                static_uow=static_uow,
            )
            static_uow.set_order_picture(order_picture=order_picture)

            self.benefit_service.apply_pending_benefits(
                pos_id=pos_id,
                static_uow=static_uow,
            )
            self.benefit_service.apply_persisted_benefits(
                pos_id=pos_id,
                static_uow=static_uow,
            )
