from logging import getLogger

from externals.device import FileDevice
from nperipherals_core.interactor.print_interactor import parse_commands
from nperipherals_core.model.device import WriterDevice, CashDrawer
from nperipherals_core.model.device_status import CashDrawerStatus, DeviceStatus
from typing import Dict

logger = getLogger(__name__)


class PrinterFileDevice(WriterDevice, FileDevice, CashDrawer):
    REQUEST_STATUS_CODE = b'\x10\x04\x01'
    SOCKET_BUF_SIZE = 1

    def __init__(
            self,
            device_configurations,  # type: Dict[unicode, unicode]
            tags_file               # type: Dict
    ):
        # type: (...) -> None

        super(PrinterFileDevice, self).__init__(logger, device_configurations)

        self.tags_file = tags_file
        self.pre_commands = parse_commands(self.tags_file, device_configurations.get("PrePrintCmds", []))
        self.post_commands = parse_commands(self.tags_file, device_configurations.get("PostPrintCmds", []))
        self.write_retries = int(device_configurations.get("Retries", 1))
        self.write_retry_sleep_in_seconds = float(device_configurations.get("RetriesSleepSeconds", 1.0))
        self.file_path = device_configurations["Path"]
        self.names = device_configurations["Name"]
        self.drawer_status = CashDrawerStatus.Closed

    @staticmethod
    def get_status(

    ):
        return DeviceStatus.Ok

    @staticmethod
    def get_drawer_status(

    ):
        # type: () -> CashDrawerStatus

        return CashDrawerStatus.Closed

    def write(
            self,
            data    # type: unicode
    ):
        # type: (...) -> None

        f = open(self.file_path, "a")
        f.write("##########START-PRINT##########\n")
        f.write(self.pre_commands)
        f.write(data)
        f.write(self.post_commands)
        f.write("\n##########PRINT-END############\n\n")
        f.close()

    def open_drawer(
            self
    ):
        # type: (...) -> None

        self.drawer_status = CashDrawerStatus.Opened

    def get_write_retries(self):
        return 1

    def get_write_retry_sleep_in_seconds(self):
        return 1
