import os
import pyvisa
from PyQt6 import QtWidgets
from LowLevelWidgetsPackage import defaultConfigForWidgets 
from LowLevelWidgetsPackage.VisaControlPackage.visaControlGUI import Ui_visaControl as GUI_Form

from DevicePackages.ArrigoPackage.ArrigoConnectionModule import ConnectionClass
from DevicePackages.DeviceStatusModule import DeviceStatusClass
class VisaControlClass(QtWidgets.QWidget):
    def __init__(self,log:defaultConfigForWidgets.LOGGER = defaultConfigForWidgets.LOGGER("ALL"),\
         ConnectionClass:ConnectionClass = ConnectionClass,\
         DeviceStatusClass:DeviceStatusClass = DeviceStatusClass, *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 VisaControl CLASS","UNNECESSARY")
        self.ui = GUI_Form() #UI form generated by UI designe
        self.ui.setupUi(self)
        self.ConnectionClass = ConnectionClass
        self.DeviceStatusClass = DeviceStatusClass

        self.ui.pb_connect.clicked.connect(self.connectButtonCallback)
        self.ui.pb_query.clicked.connect(self.queryMessage)
        self.ui.pb_write.clicked.connect(self.sendMessage)
        self.ui.pb_read.clicked.connect(self.readMessage)
        self.ui.pb_clear.clicked.connect(self.ui.te_response.clear)
        self.ui.che_read_CR.clicked.connect(self.toAppendString)
        self.ui.che_read_NL.clicked.connect(self.toAppendString)
        self.ui.che_read_custom.clicked.connect(self.toAppendString)
        self.ui.le_read_custom.textChanged.connect(self.toAppendString)
        self.ui.che_append_CR_write.clicked.connect(self.toAppendString)
        self.ui.che_append_NL_write.clicked.connect(self.toAppendString)
        self.ui.che_write_custom.clicked.connect(self.toAppendString)
        self.ui.le_write_custom.textChanged.connect(self.toAppendString)
        self.ui.le_timeout.textChanged.connect(self.updateTimeout)
        self.ui.che_autoscroll.clicked.connect(self.autoScroll)

        #Default connection
        self.ui.le_visa_string.setText(self.ConnectionClass.config_dictionary["VISASTRING"])
        self.ui.le_timeout.setText(self.ConnectionClass.config_dictionary["TIMEOUT"])
        self.ui.le_command.setText(self.ConnectionClass.config_dictionary["SELF_CHECK_COMMAND"])

        #Read termination
        if self.ConnectionClass.config_dictionary["READTERMINATION"] == "\r":
            self.ui.che_read_CR.setChecked(True)

        if self.ConnectionClass.config_dictionary["READTERMINATION"] == "\n":
            self.ui.che_read_NL.setChecked(True)

        else:
            self.ui.che_read_custom.setChecked(True)
            self.ui.le_read_custom.setText(self.ConnectionClass.config_dictionary["READTERMINATION"])

        #Write termination
        if self.ConnectionClass.config_dictionary["WRITETERMINATION"] == "\r":
            self.ui.che_append_CR_write.setChecked(True)

        if self.ConnectionClass.config_dictionary["WRITETERMINATION"] == "\n":
            self.ui.che_append_NL_write.setChecked(True)

        else:
            self.ui.che_write_custom.setChecked(True)
            self.ui.le_write_custom.setText(self.ConnectionClass.config_dictionary["WRITETERMINATION"])


        #Connection status
        if self.DeviceStatusClass.connection_status != self.DeviceStatusClass.STATE.CONNECTED:
            self.ui.pb_connect.setText("Connect")
            self.disableControls()
        
        else:
            self.ui.pb_connect.setText("Disconnect")


    def updateTimeout(self):
        if self.DeviceStatusClass.connection_status == self.DeviceStatusClass.STATE.CONNECTED:
            self.ConnectionClass._visa_instrument.timeout = int(self.ui.le_timeout.text())

    def autoScroll(self):
        if self.ui.che_autoscroll.isChecked():
            self.ui.te_response.verticalScrollBar().setValue(self.ui.te_response.verticalScrollBar().maximum())

    def toAppendString(self):
        """ Update VISA SEttings accordingly o GUI string termination"""
        append_string_read = ""
        if self.ui.che_read_CR.isChecked():
            append_string_read += "\r"
        if self.ui.che_read_NL.isChecked():
            append_string_read += "\n"
        if self.ui.che_read_custom.isChecked():
            append_string_read += self.ui.le_read_custom.text()

        
        append_string_write = ""
        if self.ui.che_append_CR_write.isChecked():
            append_string_write += "\r"
        if self.ui.che_append_NL_write.isChecked():
            append_string_write += "\n"
        if self.ui.che_write_custom.isChecked():
            append_string_write += self.ui.le_write_custom.text()

        if self.DeviceStatusClass.connection_status == self.DeviceStatusClass.STATE.CONNECTED:
            self.ConnectionClass._visa_instrument.read_termination =  append_string_read
            self.ConnectionClass._visa_instrument.write_termination = append_string_write

    def queryMessage(self):
        self.ui.te_response.append(f"Query: {self.ui.le_command.text()}")
        status,message = self.ConnectionClass.queryMessage(self.ui.le_command.text())
        self.ui.te_response.append(f"Result: {message}")
        self.autoScroll()


    def sendMessage(self):
        self.ui.te_response.append(f"Write: {self.ui.le_command.text()}")
        self.ConnectionClass.sendMessage(self.ui.le_command.text())
        self.autoScroll()

    def readMessage(self):
        status,message = self.ConnectionClass.readMessage()
        self.ui.te_response.append(f"Read: {message}")
        self.autoScroll()

    
    def connectButtonCallback(self):
        self.log.log(f"CONNECT BUTTON PRESSED: status = {self.DeviceStatusClass.connection_status}","INFO")
        if self.DeviceStatusClass.connection_status == self.DeviceStatusClass.STATE.CONNECTED:#connected
            status, message = self.ConnectionClass.disconnect()
            if status == False: #disconnecting unsesccesful
                self.ui.te_response.append(f"Disconnection failed: {message}")
            self.disableControls()
            self.ui.pb_connect.setText("CONNECT")
            self.DeviceStatusClass.connection_status = self.DeviceStatusClass.STATE.DISCONNECTED

        elif self.DeviceStatusClass.connection_status != self.DeviceStatusClass.STATE.CONNECTED: #not connected
            self.ConnectionClass.config_dictionary["VISASTRING"] = self.ui.le_visa_string.text()
            status,message = self.ConnectionClass.connect()
            if status== False: #Connecting unsesccesful
                self.ui.te_response.append(f"Connection failed: {message}")
                return
            self.enableControls()
            self.ui.pb_connect.setText("DISCONNECT")
            self.DeviceStatusClass.connection_status = self.DeviceStatusClass.STATE.CONNECTED
    

    def enableControls(self):
        self.ui.le_command.setEnabled(True)
        self.ui.pb_query.setEnabled(True)
        self.ui.pb_read.setEnabled(True)
        self.ui.pb_write.setEnabled(True)
        self.ui.che_append_CR_write.setEnabled(True)
        self.ui.che_append_NL_write.setEnabled(True)
        self.ui.che_write_custom.setEnabled(True)
        self.ui.le_write_custom.setEnabled(True)
        self.ui.che_read_CR.setEnabled(True)
        self.ui.che_read_NL.setEnabled(True)
        self.ui.che_read_custom.setEnabled(True)
        self.ui.le_read_custom.setEnabled(True)

    def disableControls(self):
        self.ui.le_command.setEnabled(False)
        self.ui.pb_query.setEnabled(False)
        self.ui.pb_read.setEnabled(False)
        self.ui.pb_write.setEnabled(False)
        self.ui.che_append_CR_write.setEnabled(False)
        self.ui.che_append_NL_write.setEnabled(False)
        self.ui.che_write_custom.setEnabled(False)
        self.ui.le_write_custom.setEnabled(False)
        self.ui.che_read_CR.setEnabled(False)
        self.ui.che_read_NL.setEnabled(False)
        self.ui.che_read_custom.setEnabled(False)
        self.ui.le_read_custom.setEnabled(False)

    

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

    app = QtWidgets.QApplication([])
    window = VisaControlClass(QtWidgets.QWidget)
    window.show()
    app.exec()