import os
import sys
from PyQt6 import QtWidgets
from PyQt6.QtCore import pyqtSignal, pyqtSlot
from LowLevelWidgetsPackage import defaultConfigForWidgets
from LowLevelWidgetsPackage.DeviceStatusIndicatorPackage.DeviceStatusIndicatorGUI import Ui_DviceStatusIndicator
from DevicePackages.DeviceStatusModule import DeviceStatusClass

defaultConfig = { #just default values Will be overwritten by main program
 "DEVICENAME" : "Some Device Name",
 "COMMUNICATION": "Communication protocol",
 "VISASTRING" : 'For example in case of VISA protocol use VISA string',
 "TIMEOUT": "1000",
 "PREFIXFORTESTS": "TESTPREFIXFORDEVICE",
 "IDENTRESPONSE": "MESSAGE that is expected from device",
 "READTERMINATION": "expected termination of the message",
 "WRITETERMINATION": "TO append to the end of the message",
 "CONNECTATSTARTUP": True,
 "NEEDSTOBECONNECTED": False}

defaultDeviceStatusClass = DeviceStatusClass()

#class SignalClass(QtCore.QObject):
#    statusSignal = pyqtSignal(list)

class DeviceStatusIndicatorClass(QtWidgets.QWidget):
    def __init__(self,log:defaultConfigForWidgets.LOGGER = defaultConfigForWidgets.LOGGER("ALL"),\
        device_config:dict = defaultConfig,\
        device_status_class:DeviceStatusClass =  defaultDeviceStatusClass, *args, **kwargs):#args = multiple input variables, **kvargs multiple keyword variables (dictionaries, touples etc.)
    ################ INIT Function ##################
        super().__init__(*args, **kwargs)#super inherits all methods and properties from its parent  (QWIDGET classes)
        #Load UI forms creaated in QTdDesigner
        self.log = log
        self.log.log("STARTING DeviceStatusIndicator CLASS","UNNECESSARY")
        self.ui = Ui_DviceStatusIndicator() #UI form generated by UI designe
        self.ui.setupUi(self)
        self.deviceStatusClass = device_status_class
        self.deviceStatusClass.signals.property_changes.connect(self.updateSenderValue)
        self.deviceConfig = device_config
        self._name = "DeviceStatusIndicator"
        self.updateAllValues()

    @pyqtSlot(str,str,str)
    def updateSenderValue(self, property_name:str, new_value:str, sender_class_name:str):
        self.log.log(f"DeviceStatusIndicatorClass: Received Signal from {sender_class_name} with property {property_name} and value {new_value}","SIGNAL")
        match property_name:
            case "_connection_status":
                self.ui.la_connection.setText(new_value)
            case "last_fault_description":
                self.ui.te_fault_description.setText(new_value)
            case "last_fault_time":
                self.ui.la_last_fault_time.setText(str(new_value))
            case "last_startUp_time":
                self.ui.la_last_startup_time.setText(str(new_value))
            case "last_self_check_time":
                self.ui.la_last_self_check_time.setText(str(new_value))
            case "test_status":
                self.ui.la_test_status.setText(new_value)
            case "device_name":
                self.ui.la_device_name.setText(new_value)
            case _: #default
                self.log.log(f"Property {property_name} not found","ERROR")

    def updateAllValues(self):
        self.ui.la_connection.setText(self.deviceStatusClass.connection_status)
        self.ui.te_fault_description.setText(self.deviceStatusClass.last_fault_description)
        self.ui.la_last_fault_time.setText(str(self.deviceStatusClass.last_fault_time))
        self.ui.la_last_startup_time.setText(str(self.deviceStatusClass.last_startUp_time))
        self.ui.la_last_self_check_time.setText(str(self.deviceStatusClass.last_self_check_time))
        self.ui.la_test_status.setText(self.deviceStatusClass.test_status)
        self.ui.la_device_name.setText(self.deviceConfig["DEVICENAME"])

        row = 0
        self._clearLayout(self.ui.grid_config_file_layout)
        for keys in self.deviceConfig:
            self.ui.grid_config_file_layout.addWidget(QtWidgets.QLabel(f"{keys}:"),row,0)
            if "\n" in str(self.deviceConfig[keys]) or "\r" in str(self.deviceConfig[keys]):
                widget = QtWidgets.QTextEdit(str(self.deviceConfig[keys]))
                widget.setMaximumHeight(40)
                widget.setReadOnly(True)
                self.ui.grid_config_file_layout.addWidget(widget,row,1)
            else:
                self.ui.grid_config_file_layout.addWidget(QtWidgets.QLabel(str(self.deviceConfig[keys])),row,1)
            self.log.log(f"{keys} : {self.deviceConfig[keys]}","INFO")
            row += 1

    def _clearLayout(self,layout):
        for i in reversed(range(layout.count())): 
            layout.itemAt(i).widget().setParent(None)

    def setName(self,name:str):
        #to distinguish between different widgets change self.name -> this name will be emit in signals
        self._name = name

if __name__ == "__main__":
    if os.path.exists("DeviceStatusIndicatorGUI.py"):
        os.remove("DeviceStatusIndicatorGUI.py")
    bashCommand = "pyuic6 -o DeviceStatusIndicatorGUI.py DeviceStatusIndicator.ui"
    os.system(bashCommand)

    app1 = QtWidgets.QApplication([])
    window1 = DeviceStatusIndicatorClass(QtWidgets.QWidget)
    window1.show()
    app1.exec()