import json

from typing import (
    Dict,
)

from .token import TK_SLCTRL_PMGR_GET_TENDERS

from messagebus import (
    MessageBus,
    Message,
    DataType,
    DefaultToken,
)


class ProductService(object):

    def __init__(
        self,               # type: ProductService
        message_bus,        # type: MessageBus
    ):
        # type: (...) -> None

        self.message_bus = message_bus
        self.component_name = "ORDERMGR"

    def get_tenders_list(
        self,       # type: ProductService
    ):
        # type: (...) -> Dict

        msg = self._get_tenders()
        json_data = json.loads(msg.data)
        return _byteify(json_data)

    def get_tenders_dict(
        self,       # type: ProductService
    ):
        # type: (...) -> Dict

        msg = self._get_tenders()
        tenders = json.loads(msg.data)
        tenders_dict = {}
        for tender in tenders:
            tenders_dict[tender["id"]] = tender

        return _byteify(tenders_dict)

    def _get_tenders(
        self,       # type: ProductService
    ):
        # type: (...) -> Message

        msg = self.message_bus.send_message(
            component=self.component_name,
            message=Message(
                token=TK_SLCTRL_PMGR_GET_TENDERS,
                data_type=DataType.param,
            )
        )

        if msg.token != DefaultToken.TK_SYS_ACK:
            raise RuntimeError("Could not retrieve tenders")

        return msg


def _byteify(input):
    if isinstance(input, dict):
        return {_byteify(key): _byteify(value) for key, value in input.iteritems()}

    if isinstance(input, list):
        return [_byteify(element) for element in input]

    if isinstance(input, unicode):
        return input.encode('utf-8')

    return input
