from logging import Logger

from cfgtools import Group
from modelcommon.model import SitefResponse

from dialogmanager import DialogManager
from mbcontextmessagehandler import MbContextMessageBus
from typing import (
    Any,
    Union,
    Optional,
)

from model import (
    CancelPaymentOrderData,
    ConfirmFinishPaymentData,
    TestConnectionData,
    StartPaymentData,
)
from paymentprocessor import PaymentProcessor
from util import Cache
from ._SitefPaymentProcessor import SitefPaymentProcessor


class SitefDigitalWalletsPaymentProcessor(PaymentProcessor):
    def __init__(
        self,
        message_bus,        # type: MbContextMessageBus
        dialog_manager,     # type: DialogManager
        config,             # type: Group
        logger,             # type: Logger
        cache,              # type: Cache
    ):
        # type: (...) -> None

        super(SitefDigitalWalletsPaymentProcessor, self).__init__(message_bus, dialog_manager, config, logger, cache)
        self.sitef_processor = SitefPaymentProcessor(message_bus, dialog_manager, config, logger, cache)
        self.show_qr_code = config.find_value("ShowQRCode", "false").lower() == "true"
        self.allowed_payments = config.find_values("AllowedPayments") or []
        self.forbidden_payments = config.find_values("ForbiddenPayments") or []

        default_disabled_payments = ['10', '17', '18', '19', '27', '28', '29', '34', '35', '36', '42']
        self.disabled_payments = config.find_values("DisabledPayments") or default_disabled_payments

        self.additional_data = self._get_additional_data()

    def connection_status(
        self,
        test_connection_data    # type: TestConnectionData
    ):
        # type: (...) -> bool

        return self.sitef_processor.connection_status(test_connection_data=test_connection_data)

    def add_payment(
        self,                   # type: SitefDigitalWalletsPaymentProcessor
        start_payment_data,     # type: StartPaymentData
    ):
        # type: (...) -> Any[Union[SitefResponse, str]]

        return self.sitef_processor.add_payment(
            start_payment_data=start_payment_data,
            additional_params=self.additional_data,
        )

    def cancel_payment_order(
        self,
        cancel_payment_order_data,  # type: CancelPaymentOrderData
        additional_params="",       # type: Optional[str]
    ):
        # type: (...) -> Any[Union[SitefResponse, str]]

        return self.sitef_processor.cancel_payment_order(cancel_payment_order_data=cancel_payment_order_data)

    def cancel_payment(self):
        return self.sitef_processor.cancel_payment()

    def finish_payment(self, finish_payment_data):
        return self.sitef_processor.finish_payment(finish_payment_data)

    def confirm_finish_payment(
        self,
        confirm_finish_payment_data     # type: ConfirmFinishPaymentData
    ):
        # type: (...) -> None

        pass

    def get_name(self):
        return self.sitef_processor.get_name()

    def get_document(
        self,
        pos_id      # type: str
    ):
        # type: (...) -> str

        return self.sitef_processor.get_document(pos_id)

    def stop(self):
        self.sitef_processor.stop()

    def get_last_receipt(
        self,
        eft_processor,     # type: str
    ):
        # type: (...) -> Optional[str]

        return self.sitef_processor.get_last_receipt(eft_processor=eft_processor)

    def _get_additional_data(self):
        additional_data_list = []

        if self.disabled_payments:
            additional_data_list.append("[{}]".format(';'.join(self.disabled_payments)))

        if self.show_qr_code:
            additional_data_list.append("{DevolveStringQRCode=1}")

        if self.allowed_payments:
            additional_data_list.append("{{CarteirasDigitaisHabilitadas={}}}".format(';'.join(self.allowed_payments)))

        if self.forbidden_payments:
            additional_data_list.append("{{RestricoesCarteirasDigitais={}}}".format(';'.join(self.forbidden_payments)))

        return ';'.join(additional_data_list)

    def get_qr_code_config(
        self,   # type: SitefDigitalWalletsPaymentProcessor
    ):
        # type: () -> bool

        return self.sitef_processor.get_qr_code_config()

