from application.model import (
    BenefitAppliers,
    OperationDescription,
)
from application.model.configuration import Configurations
from application.model.repository.benefit_applier import DefaultBenefitApplierRepository
from application.repository.pos import DBRepository
from typing import (
    Optional,
    Dict,
)


class BurnBenefitInteractor(object):

    def __init__(self, configs, db_repository, benefit_appliers_repositories):
        # type: (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

    def burn_benefit(self, benefit_id, originator_pos_id, benefit_applier, retry_quantity=0):
        # type: (str, int, BenefitAppliers, Optional[int]) -> None

        success = False
        applier_name = benefit_applier.split("|")[0]
        try:
            message = "Burning benefit. BenefitId: {}; OriginatorPosId: {}; BenefitApplier: {}; Try: {}"
            self.logger.info(message.format(benefit_id, originator_pos_id, applier_name, retry_quantity))
            if benefit_applier not in [None, 'None', '']:
                self.benefit_appliers_repositories[applier_name].burn_benefit(
                    benefit_id=benefit_id,
                    pos_id=originator_pos_id,
                )
            success = True

        except Exception as _:
            self.logger.exception("Error burning benefit: {}".format(benefit_id))
        finally:
            self.db_repository.manage_operation_status(
                success,
                benefit_id,
                originator_pos_id,
                OperationDescription.BURNED,
                applier_name,
                retry_quantity
            )
