from xml.etree import cElementTree as eTree

from application.interactor import UnlockBenefitInteractor
from application.model import BenefitAppliers
from application.model.configuration import Configurations
from application.model.repository.benefit_applier import DefaultBenefitApplierRepository
from application.repository.pos import DBRepository
from application.repository.pos.utils import find_order_benefits_id
from typing import Dict

from application.services import TableService


class OrderModifiedVoidInteractor(object):
    def __init__(
        self,                               # type: OrderModifiedVoidInteractor
        unlock_benefit_interactor,          # type: UnlockBenefitInteractor
        configs,                            # type: Configurations
        db_repository,                      # type: DBRepository
        benefit_appliers_repositories,      # type: Dict[BenefitAppliers: DefaultBenefitApplierRepository]
        table_service,                      # type: TableService
    ):
        # type: (...) -> None

        self.configs = configs
        self.logger = self.configs.logger
        self.db_repository = db_repository
        self.benefit_appliers_repositories = benefit_appliers_repositories
        self.unlock_benefit_interactor = unlock_benefit_interactor
        self.table_service = table_service

    def unlock_voided_benefit(self, current_pos_id, originator_pos_id, order_id, order_picture):
        # type: (int, int, int, eTree) -> None

        all_histories = order_picture.findall("StateHistory/State")
        if len(all_histories) > 0 and all_histories[-1].get("stateId") == "8":
            return

        order_benefits_id = find_order_benefits_id(self.logger, order_picture)
        if not order_benefits_id:
            return

        message = "Benefits founded to unlock: {}; Current/Originator PosId: {}/{}; OrderId: {}"
        self.logger.info(message.format(order_benefits_id, current_pos_id, originator_pos_id, order_id))

        table_picture = self.table_service.get_table_picture(
            pos_id=originator_pos_id,
            order_picture=order_picture,
        )

        for benefit_id in order_benefits_id:
            benefit_applier = self.db_repository.get_benefit_applier_by_db(benefit_id)
            if benefit_applier not in [None, 'None', '']:
                self.unlock_benefit_interactor.unlock_benefit(
                    benefit_id=benefit_id,
                    originator_pos_id=originator_pos_id,
                    benefit_applier=benefit_applier,
                    order_picture=order_picture,
                    table_picture=table_picture,
                )
