import json
from typing import Optional

from bustoken import (
    TK_NDISCOUNT_ON_TABLE_REOPEN,
    TK_NDISCOUNT_ON_TABLE_OPEN,
    TK_NDISCOUNT_ON_TAB_OPEN,
)
from msgbus import (
    FM_PARAM,
    MBException,
    MBEasyContext,
    TK_SYS_ACK,
)
from systools import sys_log_info


class DiscountService(object):
    @staticmethod
    def on_service_open(
        mbcontext,      # type: MBEasyContext
        pos_id,         # type: int
        table_id,       # type: str
        is_tab=False,   # type: Optional[bool]
    ):
        # type: (...) -> int

        token = TK_NDISCOUNT_ON_TAB_OPEN if is_tab else TK_NDISCOUNT_ON_TABLE_OPEN

        data = json.dumps(dict(
            pos_id=pos_id,
            table_id=table_id,
        ))
        try:
            msg = mbcontext.MB_EasySendMessage(
                dest_name="nDiscount",
                token=token,
                format=FM_PARAM,
                data=data,
                timeout=30000000,
            )

            if msg.token == TK_SYS_ACK:
                order_id = msg.data
                return order_id

        except MBException as ex:
            sys_log_info(message="Error on_service_open: {0}".format(ex.message))

    @staticmethod
    def on_reopen_service(
        mbcontext,  # type: MBEasyContext
        pos_id,     # type: int
        table_id,   # type: int
    ):
        # type: (...) -> Optional[bool]

        data = json.dumps(dict(
            pos_id=pos_id,
            table_id=table_id,
        ))
        try:
            mbcontext.MB_EasySendMessage(
                dest_name="nDiscount",
                token=TK_NDISCOUNT_ON_TABLE_REOPEN,
                format=FM_PARAM,
                data=data,
                timeout=30000000,
            )
        except MBException as ex:
            sys_log_info(message="Error on_reopen_service: {0}".format(ex.message))
            return False



