import json
import logging
import time

from bustoken import TK_NDISCOUNT_GET_BENEFITS
from msgbus import (
    FM_PARAM,
    TK_SYS_ACK,
)
from sysactions import send_message

from model.customexception import ErrorGettingBenefits


class NDiscountInteractor(object):
    def __init__(self):
        # type: () -> None
        self.logger = logging.getLogger("PosActions")

    def get_benefits(
        self,           # type: NDiscountInteractor
        pos_id,         # type: int
        only_visible,   # type: bool
    ):
        # type: (...) -> json

        self.logger.info("Getting benefits for POS: {}".format(pos_id))
        retry = 0
        while retry < 3:
            time.sleep(0.5 * retry)
            try:
                data = json.dumps(dict(posId=pos_id, only_visible=only_visible))
                response = send_message(
                    dest_name="nDiscount",
                    token=TK_NDISCOUNT_GET_BENEFITS,
                    format=FM_PARAM,
                    data=data,
                    timeout=30000000,
                )
                if response.token == TK_SYS_ACK:
                    return json.loads(response.data)
            except Exception as ex:
                self.logger.warn("Error getting benefits data: {} - Retry attempt: {}".format(ex.message, retry))

            retry += 1

        self.logger.exception("[get_benefits] benefits retry failed")
        raise ErrorGettingBenefits()

    def test_connection(
        self,   # type: NDiscountInteractor
    ):
        # type: (...) -> bool
        try:
            data = json.dumps(dict())
            response = send_message("nDiscount", TK_NDISCOUNT_GET_BENEFITS, FM_PARAM, data, timeout=30000000)
            if response:
                return True
            return False
        except (Exception,) as _:
            self.logger.exception("Unreachable component nDiscount")
            return False
