import json
import logging

from sysactions import send_message
from msgbus import TK_SYS_ACK, FM_PARAM, MBMessage
from model.customexception import ErrorAddingBenefits, ErrorGettingBenefits
from bustoken import TK_NDISCOUNT_ADD_BENEFIT, TK_NDISCOUNT_REMOVE, TK_NDISCOUNT_GET_BENEFITS


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

    @staticmethod
    def add_benefit(pos_id, benefit_id, benefit):
        # type: (int, str, json) -> bool

        data = json.dumps(dict(posId=pos_id, benefitId=benefit_id, benefit=benefit))

        response = send_message("nDiscount", TK_NDISCOUNT_ADD_BENEFIT, FM_PARAM, data, timeout=30000000)
        if response.token == TK_SYS_ACK:
            return True

        raise ErrorAddingBenefits(response.data)

    @staticmethod
    def get_benefits(pos_id, only_visible):
        # type: (int, bool) -> json

        data = json.dumps(dict(posId=pos_id, only_visible=only_visible))

        response = send_message("nDiscount", TK_NDISCOUNT_GET_BENEFITS, FM_PARAM, data, timeout=30000000)
        if response.token == TK_SYS_ACK:
            return json.loads(response.data)

        raise ErrorGettingBenefits(response.data)

    @staticmethod
    def remove_benefits(pos_id, benefit_ids=None):
        # type: (str, array) -> MBMessage

        data = json.dumps(dict({"pos_id": pos_id, "benefit": benefit_ids}))
        return send_message("nDiscount", TK_NDISCOUNT_REMOVE, FM_PARAM, data, timeout=30000000)

    @staticmethod
    def remove_benefit(pos_id, benefit_id):
        # type: (str, int) -> MBMessage

        data = json.dumps(dict({"pos_id": pos_id, "benefit": benefit_id}))
        return send_message("nDiscount", TK_NDISCOUNT_REMOVE, FM_PARAM, data, timeout=30000000)

    @staticmethod
    def test_connection():
        # 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 _:
            return False
