from logging import Logger
from xml.etree import cElementTree as eTree

from mbcontextmessagehandler import MbContextMessageBus
from messagebus import (
    Message,
    DataType,
)
from msgbus import (
    TK_PRN_PRINT,
    TK_SYS_NAK,
    MBTimeout,
    MBException,
)
from sysactions import get_used_service
from typing import Optional


class PrinterService(object):
    def __init__(
        self,
        logger,         # type: Logger
        message_bus,    # type: MbContextMessageBus
    ):
        # type: (...) -> None

        self.logger = logger
        self.message_bus = message_bus

    def send_print_data(
        self,           # type: PrinterService
        model,          # type: eTree
        response,       # type: str
    ):
        # type: (...) -> Optional[Message]

        current_printer = get_used_service(
            model=model,
            service_type="printer",
        )

        thirty_seconds = 30 * 1000000
        message = Message(
            token=TK_PRN_PRINT,
            data_type=DataType.param,
            data=response,
            timeout=thirty_seconds,
        )

        print_response = None
        try:
            print_response = self.message_bus.send_message(
                component=current_printer,
                message=message,
            )
            if print_response.token == TK_SYS_NAK:
                self.logger.error("Cannot print data receive NAK")
        except(MBTimeout, MBException) as _:
            self.logger.exception("MB error print data")
        except Exception as _:
            self.logger.exception("Error print data")

        return print_response
