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


class OrderModifiedVoidInteractor(object):

    def __init__(self, unlock_benefit_interactor, configs, db_repository, benefit_appliers_repositories):
        # type: (UnlockBenefitInteractor, Configurations, DBRepository, Dict[BenefitAppliers: DefaultBenefitApplierRepository]) -> 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

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

        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))

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