from PyQt5.QtCore import QObject

import numpy as np
import ast
import socket

import tcptools as TCP
import globalvars

from channelInfoWidgetClass import channelInfoWidget

class channelInfo(QObject):
    def __init__(self, channel_num, temp_field, out_field, enable_field, tabnumber, activTabWidget, parent):
        super(channelInfo,self).__init__(parent)
        self.widget_obj = channelInfoWidget(self)
        self.channel_num = channel_num

        self.temp_field = temp_field
        self.out_field = out_field
        self.enable_field = enable_field

        self.tabNumber = tabnumber
        self.activTabWidget = activTabWidget

        self.data_length   = 64
        self.temp_data     = np.array([21.0] * self.data_length)
        self.error_data    = np.array([0.0] * self.data_length)
        self.output_data   = np.array([0.0] * self.data_length)
        self.interror_data = np.array([0.0] * self.data_length)

        self.temp_plot = self.widget_obj.temp_plot.plot(y=self.temp_data,clickable=True)
        self.output_plot = self.widget_obj.output_plot.plot(y=self.output_data,clickable=True)
        self.error_plot = self.widget_obj.error_plot.plot(y=self.error_data,clickable=True)

        self.widget_obj.setpointBox.valueChanged.connect(self.setpointChanged)
        self.widget_obj.kpBox.valueChanged.connect(self.kpChanged)
        self.widget_obj.kiBox.valueChanged.connect(self.kiChanged)
        self.widget_obj.kdBox.valueChanged.connect(self.kdChanged)
        self.widget_obj.PIDenableButton.clicked.connect(self.PIDenableButtonChanged)
        self.widget_obj.OutputButton.clicked.connect(self.OutputButtonChanged)


    def update(self):
        if globalvars.conStatus:
            TCP.send_cmd(globalvars.sock, 'CMD:\tGET_RUN_VALUES\t'+str(self.channel_num)+'\t')
            msg = TCP.recv_msg(globalvars.sock)

            #ans = str2num(msg)
            try:
                ans = ast.literal_eval(msg)
            except ValueError:
                ans = [100, 0, 0]
            

            self.temp_data = np.roll(self.temp_data, -1)
            self.temp_data[self.data_length-1] = ans[0]
            self.temp_field.setText("{:.4f}".format(ans[0]))

            self.error_data = np.roll(self.error_data, -1)
            self.error_data[self.data_length-1] = ans[1]

            self.output_data = np.roll(self.output_data, -1)
            self.output_data[self.data_length-1] = ans[2]
            self.out_field.setText("{:.4f}".format(ans[2]))

            if self.tabNumber == self.activTabWidget.currentIndex():
                self.temp_plot.setData(y=self.temp_data)
                self.error_plot.setData(y=self.error_data)
                self.output_plot.setData(y=self.output_data)


    def setpointChanged(self):
        if globalvars.conStatus:
            TCP.send_cmd(globalvars.sock, 'CMD:\tSET_SETPOINT\t'+str(self.channel_num)+'\t'+str(self.widget_obj.setpointBox.value())+'\t')
            ans = TCP.recv_msg(globalvars.sock)
            print(ans)
            globalvars.settings["ch{0}".format(self.channel_num)]["setpoint"] = self.widget_obj.setpointBox.value()

    def kpChanged(self):
        if globalvars.conStatus:
            TCP.send_cmd(globalvars.sock, 'CMD:\tSET_KP\t'+str(self.channel_num)+'\t'+str(self.widget_obj.kpBox.value())+'\t')
            ans = TCP.recv_msg(globalvars.sock)
            print(ans)

    def kiChanged(self):
        if globalvars.conStatus:
            TCP.send_cmd(globalvars.sock, 'CMD:\tSET_KI\t'+str(self.channel_num)+'\t'+str(self.widget_obj.kiBox.value())+'\t')
            ans = TCP.recv_msg(globalvars.sock)
            print(ans)

    def kdChanged(self):
        if globalvars.conStatus:
            TCP.send_cmd(globalvars.sock, 'CMD:\tSET_KD\t'+str(self.channel_num)+'\t'+str(self.widget_obj.kdBox.value())+'\t')
            ans = TCP.recv_msg(globalvars.sock)
            print(ans)

    def PIDenableButtonChanged(self):
        if globalvars.conStatus:
            if self.widget_obj.PIDenableButton.isChecked():
                self.widget_obj.PIDenableButton.setStyleSheet("background-color: rgb(0,255,0)")
                self.widget_obj.OutputButton.setEnabled(False)
                TCP.send_cmd(globalvars.sock, 'CMD:\tLOCK\t'+str(self.channel_num)+'\t')
                ans = TCP.recv_msg(globalvars.sock)
                print(ans)
                self.enable_field.setStyleSheet("background-color: rgb(0,255,0)")
            else:
                self.widget_obj.PIDenableButton.setStyleSheet("background-color: rgb(255,0,0)")
                self.widget_obj.OutputButton.setEnabled(True)
                TCP.send_cmd(globalvars.sock, 'CMD:\tIDLE\t'+str(self.channel_num)+'\t')
                ans = TCP.recv_msg(globalvars.sock)
                print(ans)
                self.enable_field.setStyleSheet("background-color: rgb(255,0,0)")
        else:
            self.widget_obj.PIDenableButton.setChecked(False)

    def OutputButtonChanged(self):
        if globalvars.conStatus:
            TCP.send_cmd(globalvars.sock, 'CMD:\tSET_VOLTAGE\t'+str(self.channel_num)+'\t'+str(self.widget_obj.outputBox.value())+'\t')
            ans = TCP.recv_msg(globalvars.sock)
            print(ans)

    def setEnabled(self, val):
        self.widget_obj.setEnabled(val)

    def loadSettings(self):
        if globalvars.remoteSettings:
            TCP.send_cmd(globalvars.sock,"CMD:\tGET_SETPOINT\t{0}\t".format(self.channel_num))
            setpoint = float(TCP.recv_msg(globalvars.sock))
            self.widget_obj.setpointBox.blockSignals(True)
            self.widget_obj.setpointBox.setValue(setpoint)
            self.widget_obj.setpointBox.blockSignals(False)

            TCP.send_cmd(globalvars.sock,"CMD:\tGET_KP\t{0}\t".format(self.channel_num))
            kp = float(TCP.recv_msg(globalvars.sock))
            self.widget_obj.kpBox.blockSignals(True)
            self.widget_obj.kpBox.setValue(kp)
            self.widget_obj.kpBox.blockSignals(False)

            TCP.send_cmd(globalvars.sock,"CMD:\tGET_KI\t{0}\t".format(self.channel_num))
            ki = float(TCP.recv_msg(globalvars.sock))
            self.widget_obj.kiBox.blockSignals(True)
            self.widget_obj.kiBox.setValue(ki)
            self.widget_obj.kiBox.blockSignals(False)

            TCP.send_cmd(globalvars.sock,"CMD:\tGET_KD\t{0}\t".format(self.channel_num))
            kd = float(TCP.recv_msg(globalvars.sock))
            self.widget_obj.kdBox.blockSignals(True)
            self.widget_obj.kdBox.setValue(kd)
            self.widget_obj.kdBox.blockSignals(False)

            TCP.send_cmd(globalvars.sock,"CMD:\tGET_PID_STATUS\t{0}\t".format(self.channel_num))
            enabled = int(TCP.recv_msg(globalvars.sock))
            print(enabled)
            self.widget_obj.PIDenableButton.setChecked(enabled)
            if self.widget_obj.PIDenableButton.isChecked():
                self.widget_obj.PIDenableButton.setStyleSheet("background-color: rgb(0,255,0)")
                self.widget_obj.OutputButton.setEnabled(False)
                self.enable_field.setStyleSheet("background-color: rgb(0,255,0)")
            else:
                self.widget_obj.PIDenableButton.setStyleSheet("background-color: rgb(255,0,0)")
                self.widget_obj.OutputButton.setEnabled(True)
                self.enable_field.setStyleSheet("background-color: rgb(255,0,0)")

        else:
            #Set settings from file and trigger sending to server
            self.widget_obj.setpointBox.setValue(float(globalvars.settings["ch{0}".format(self.channel_num)]["setpoint"]))
            self.widget_obj.kpBox.setValue(float(globalvars.settings["ch{0}".format(self.channel_num)]["kp"]))
            self.widget_obj.kiBox.setValue(float(globalvars.settings["ch{0}".format(self.channel_num)]["ki"]))
            self.widget_obj.kdBox.setValue(float(globalvars.settings["ch{0}".format(self.channel_num)]["kd"]))
            self.widget_obj.PIDenableButton.setChecked(bool(globalvars.settings["ch{0}".format(self.channel_num)]["PIDenabled"]))
