import json
from logging import Logger

from bustoken import TK_REMOTE_ORDER_GET_DELIVERY_BRANDS
from msgbus import (
    MBEasyContext,
    TK_SYS_ACK
)
from typing import (
    List,
    Optional,
)


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

        self.mb_context = mb_context
        self.logger = logger
        self.delivery_brands = None

    def get_delivery_brands(self):
        # type: (...) -> Optional[List]

        if self.delivery_brands is not None:
            return self.delivery_brands

        try:
            result = self.mb_context.MB_EasySendMessage(
                dest_name="RemoteOrder",
                token=TK_REMOTE_ORDER_GET_DELIVERY_BRANDS,
                data=""
            )
            if result.token == TK_SYS_ACK:
                self.delivery_brands = json.loads(result.data)
        except (Exception,):
            self.logger.exception("Error getting delivery brands")
            return None

        return self.delivery_brands or []
