'''
Created on 8 apr 2019

@author: Emanuele Trabattoni
'''

import sys
import datetime
import PyQt5.QtWidgets
from MKPrint_GUI import Ui_MainWindow
from printer import MarkoPrinter


class MainWindow(PyQt5.QtWidgets.QMainWindow):
    def __init__(self, configFilePath):
        try:
            self.printer = MarkoPrinter(configFilePath)
        except FileNotFoundError as e:
            print("Configuration file error: {}".format(e))
            sys.exit(1)

        PyQt5.QtWidgets.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setFixedSize(self.maximumSize())
        self.setWindowTitle("Manda Etichette a Marcatrice")
        self.timer = PyQt5.QtCore.QTimer()
        self.ui.btn_connect.clicked.connect(self.toggla_connessione)
        self.ui.btn_upload.clicked.connect(self.upload)
        self.ui.btn_upload.setEnabled(False)
        self.ui.rad_dataOn.setChecked(True)
        self.ui.prg_inkLevel.setTextVisible(True)

    def updateStatusView(self):
        connessa = self.printer.connected
        self.ui.btn_upload.setEnabled(connessa)
        if connessa:
            self.ui.prg_inkLevel.setValue(self.printer.headStatus["iuse"])
            self.ui.lcd_printCount.display(
                str(self.printer.headStatus["labelCnt"]))
        else:
            self.ui.prg_inkLevel.setValue(0)
            self.ui.lcd_printCount.display('0')

    def toggla_connessione(self):
        connessa = self.printer.connected
        if connessa:
            connessa = self.printer.disconnetti()
        else:
            connessa = self.printer.connetti()
        if connessa:
            self.ui.btn_connect.setText("DISCONNETTI")
            self.ui.lbl_stat.setText("Connesso")
            self.timer.start(self.printer.settings["keepalive"])
            self.timer.timeout.connect(self.keepalive)
        else:
            self.timer.stop()
            self.ui.lbl_stat.setText("Disconnesso")
            self.ui.btn_connect.setText("CONNETTI")
        self.updateStatusView()

    def keepalive(self):
        # TODO: usare il primo argomento di keepalive (stato connessione) per aggiornare la ui
        _, statusUpdated = self.printer.keepalive()
        if statusUpdated:
            self.updateStatusView()

    def upload(self):
        if self.ui.rad_dataOn.isChecked():
            date = datetime.datetime.now()
            date = date.strftime(self.printer.data["dateformat"])
        else:
            date = ""
        descr = str(self.ui.txt_descr.toPlainText()).capitalize()
        datastr = str(self.ui.txt_model.text()).upper() + "\r" + \
            date + descr + "\r"
        response, statusUpdated = self.printer.upload(descr, datastr)
        if statusUpdated:
            self.updateStatusView()
        self.ui.lbl_stat.setText(response)

    def quit(self):
        pass


if __name__ == '__main__':
    app = PyQt5.QtWidgets.QApplication(sys.argv)
    configFilePath = "MkpWIFI/conf.json"
    window = MainWindow(configFilePath)
    window.show()
    sys.exit(app.exec_())
