import json
from logging import Logger

from msgbus import (
    MBEasyContext,
    TK_SYS_ACK
)
from messagebus import (
    TokenCreator,
    TokenPriority,
)

MSGGRP_DEVICE_MANAGER = "D"
TK_GET_USED_SERVICE = TokenCreator.create_token(TokenPriority.low, MSGGRP_DEVICE_MANAGER, "1")


class DeviceManagerService(object):
    def __init__(
        self,
        mb_context,  # type: MBEasyContext
        logger       # type: Logger
    ):
        # type: (...) -> None

        self.mb_context = mb_context
        self.logger = logger

    def get_available_kds(
        self,
        kds_id
    ):
        # type: (...) -> int

        try:
            data = json.dumps({
                "kdsId": kds_id,
                "deviceType": "display",
            })

            result = self.mb_context.MB_EasySendMessage(
                dest_name="DeviceManager",
                token=TK_GET_USED_SERVICE,
                data=data,
                timeout=5000000
            )
            if result.token == TK_SYS_ACK:
                return int(result.data.split("KDS")[-1])
        except ValueError:
            pass

        except (Exception,):
            self.logger.exception("Error getting fallback KDS for KDS Id {}".format(kds_id))

        return int(kds_id)
