from xml.etree import cElementTree as eTree

from messagebus import (
    MessageBus,
    Message,
    DataType,
    DefaultToken,
    TokenCreator,
    TokenPriority,
)
from .dto import Table
from .dto.table_xml_parser import parse_table
from .dto.exception import TableServiceException


TK_CMP_MESSAGE = TokenCreator.create_token(
    priority=TokenPriority.high,
    message_group="3",
    number="6",
)


class TableService(object):

    def __init__(
        self,           # type: TableService
        message_bus,    # type: MessageBus
        pos_id,         # type: int
    ):
        # type: (...) -> None

        self.message_bus = message_bus
        self.pos_id = pos_id
        self.table_mgr = "TABLEMGR"

    def get_table_picture(
        self,       # type: TableService
        table_id,   # type: int
    ):
        # type: (...) -> eTree.Element

        params = (
            "TABLE_PICTURE",
            self.pos_id,
            table_id,
        )
        request_data = "\x00".join((str(p) for p in params))
        msg = self.message_bus.send_message(
            component=self.table_mgr,
            message=Message(
                token=TK_CMP_MESSAGE,
                data_type=DataType.param,
                data=request_data,
                timeout=600000000,
            ),
        )
        if msg.token == DefaultToken.TK_SYS_ACK:
            return eTree.XML(msg.data)

        raise TableServiceException(description=msg.data)

    def get_table(
        self,       # type: TableService
        table_id,   # type: int
    ):
        # type: (...) -> Table

        xml_table_picture = self.get_table_picture(table_id=table_id)
        table = parse_table(table_xml=xml_table_picture)
        return table
