import json
import logging

from logging import Logger

from bustoken import (
    TK_NCOUPON_REMOVE_BENEFIT,
    TK_NCOUPON_TEST_CONNECTION,
)
from msgbus import (
    FM_PARAM,
    TK_SYS_ACK,
    MBMessage,
)
from sysactions import send_message
from typing import List


class NCouponInteractor(object):
    def __init__(self):
        # type: () -> None

        self.logger = logging.getLogger("PosActions")   # type: Logger

    def test_connection(
        self,
        pos_id,     # type: bool
    ):
        # type: (...) -> bool

        try:
            data = json.dumps({
                "posId": pos_id
            })
            response = send_message("nCoupon", TK_NCOUPON_TEST_CONNECTION, FM_PARAM, data, timeout=30000000)
            return response.token == TK_SYS_ACK
        except Exception as _:
            self.logger.exception("Error testing nCoupon connection")
            return False

    @staticmethod
    def remove_benefits(
        pos_id,             # type: str
        benefit_keys=None,  # type: List[str]
    ):
        # type: (...) -> MBMessage

        data = json.dumps(dict({"posId": pos_id, "benefitKeys": benefit_keys}))
        return send_message(
            dest_name="nCoupon",
            token=TK_NCOUPON_REMOVE_BENEFIT,
            format=FM_PARAM,
            data=data,
            timeout=30000000,
        )
