import json

from msgbus import (
    FM_PARAM,
    MBEasyContext,
    TK_SLCTRL_OMGR_SETCUSTOMPROPERTIES,
)
from typing import (
    Optional,
    Dict,
)


class OrderService(object):

    def __init__(
        self,           # type: OrderService
        mb_context,     # type: MBEasyContext
    ):
        # type: (...) -> None

        self.mb_context = mb_context

    def set_custom_property(
        self,               # type: OrderService
        pos_id,             # type: str
        key,                # type: str
        value,              # type: str
        order_id="",        # type: str
        blk_notify=False,   # type: Optional[bool]
    ):
        # type: (...) -> None

        # TODO: Change to order_api.OrderService. Did not make by update to MbContextMessageHandler==4.0.0 cause error

        request = {
            "customProperties": {key: value},
            "posId": int(pos_id),
            "orderId": order_id,
            "lineNumber": None,
            "itemId": None,
            "level": None,
            "partCode": None,
            "blkNotify": blk_notify,
        }

        self.mb_context.MB_EasySendMessage(
            dest_name="ORDERMGR",
            token=TK_SLCTRL_OMGR_SETCUSTOMPROPERTIES,
            format=FM_PARAM,
            data=json.dumps(request).encode("utf-8"),
            timeout=100 * 100000,
        )

    def set_custom_properties(
        self,               # type: OrderService
        pos_id,             # type: str
        custom_properties,  # type: Dict
        order_id,           # type: str
        blk_notify=False,   # type: Optional[bool]
    ):
        # type: (...) -> None

        # TODO: Change to order_api.OrderService. Did not make by update to MbContextMessageHandler==4.0.0 cause error
        request = {
            "customProperties": self._parse_properties(custom_properties=custom_properties),
            "posId": int(pos_id),
            "orderId": order_id,
            "lineNumber": None,
            "itemId": None,
            "level": None,
            "partCode": None,
            "blkNotify": blk_notify,
        }
        self.mb_context.MB_EasySendMessage(
            dest_name="ORDERMGR",
            token=TK_SLCTRL_OMGR_SETCUSTOMPROPERTIES,
            format=FM_PARAM,
            data=json.dumps(request).encode("utf-8"),
            timeout=100 * 100000,
        )

    @staticmethod
    def _parse_properties(
        custom_properties,  # type: Dict[str, str]
    ):
        # type: (...) -> Dict[str, str]

        properties = {}
        for key, value in custom_properties.items():
            try:
                if isinstance(value, unicode):  # noqa
                    value = value.encode("utf-8")
                fixed_value = str(value).decode("utf-8")
            except (Exception,):
                fixed_value = str(value)
            properties[key] = fixed_value

        return properties
