import sys

if "--sim-serial" in sys.argv:
    from components.dummies.serial import serial
else:
    import serial

from PyQt5.QtWidgets import QMessageBox

from .component import Component


class Serial_Label_Printer(Component):
    def __init__(self, config=None, name=None):
        super().__init__(config=config, name=name, threaded=False)

    def config_changed(self):
        self.port = self.config[self.name]["port"]
        self.baudrate = int(self.config[self.name]["baudrate"])
        self.stopbits = getattr(serial, self.config[self.name].get("stopbits", "stopbits_one").upper())
        self.parity = getattr(serial, self.config[self.name].get("parity", "parity_none").upper())
        self.bytesize = getattr(serial, self.config[self.name].get("bytesize", "eightbits").upper())
        self.read_timeout = float(self.config[self.name].get("read_timeout", 1))
        self.write_timeout = float(self.config[self.name].get("write_timeout", 1))
        self.inter_byte_timeout = self.config[self.name].get("inter_byte_timeout", None)
        if self.inter_byte_timeout is not None:
            self.inter_byte_timeout = float(self.inter_byte_timeout)

    @Component.reconfig_on_error
    def print_label(self, template, context=None):
        if context is None:
            context = {}
        # LOAD LABEL TEMPLATE
        with open(f"config/label_templates/{str(template)}", "r", errors="surrogateescape") as f:
            label = f.read()
        # LABEL PRINT
        label = label.format(**context)
        try:
            conn = serial.Serial(
                self.port,
                baudrate=self.baudrate,
                stopbits=self.stopbits,
                parity=self.parity,
                bytesize=self.bytesize,
                timeout=self.read_timeout,
                write_timeout=self.write_timeout,
                inter_byte_timeout=self.inter_byte_timeout,
            )
            conn.write(label.encode(errors="surrogateescape"))
            conn.close()
            return label
        except serial.serialutil.SerialException as e:
            QMessageBox.critical(
                None,
                "Errore Connessione Stampante",
                "Non e stato possibile connettersi alla stampante di etichette\nL'etichetta non verra stampata.\n\nErrore:\n" + str(e)
            )
            return None
        except Exception as e:
            QMessageBox.critical(
                None,
                "Errore Stampante",
                f"Non e stato possibile stampare l'etichetta.\n\nErrore:\n{e}"
            )
        return None
