import json
import base64
import time

from msgbus import TK_PRN_PRINT
from messagebus import (
    DataType,
    Message,
    MessageBus,
)


class PrinterService(object):
    def __init__(
        self,
        message_bus,    # type: MessageBus
        timeout,        # type: int
    ):
        # type: (...) -> None

        self.message_bus = message_bus
        self.timeout = timeout

    def send_to_printer(
        self,               # type: PrinterService
        printer_name,       # type: str
        text,               # type: str
    ):
        #  type: (...) -> Message

        json_data = self._format_request_data(
            text=text,
        )

        message = Message(
            token=TK_PRN_PRINT,
            data_type=DataType.json,
            data=json_data,
            timeout=self.timeout,
        )

        return self.message_bus.send_message(
            component=printer_name,
            message=message,
        )

    def _format_request_data(
        self,   # type: PrinterService
        text,   # type: str
    ):
        # type: (...) -> str

        valid_until = int(time.time() + (self.timeout / 1000000))
        data = base64.b64encode(text)
        return json.dumps({"data": data, "valid_until": str(valid_until)})
