from PyQt5 import QtWidgets, uic
from PyQt5.QtCore import QThread, pyqtSignal,pyqtSlot,Qt
from PyQt5.QtGui import QImage, QPixmap,QPalette,QColor
import sys
import asyncio
import websockets
import json
from threading import Thread 
from time import sleep, perf_counter


class SocketThread(QThread):
    ws_datalar_signal = pyqtSignal(object)
    
    def __init__(self):
        QThread.__init__(self)
    
    def run(self):
        self.messageGonder=0
        asyncio.run(self.start_server())
    
    async def wsecho(self,websocket, path):
        self.wsGnder=websocket
        async for message in websocket:
            #print(f"Received message: {message}")        

            try:
                message = json.loads(message)
                #print("messageJson:",message,type(message))
                #print("messageJson:",message)
                self.ws_datalar_signal.emit(message)
                #rint(message['nereye'])        # Output: iolar
            except:
                pass


    async def start_server(self):
        async with websockets.serve(self.wsecho, "192.168.1.4", 5001):
            await asyncio.Future()  # run forever
    
    async def gelenData(self,gelen):
        #await self.dataGonder(gelen)
        #print(" gelenData gelen:",gelen)
        await self.wsGnder.send(gelen)

    
    async def dataGonder(self,gelen):
        async with websockets.connect("192.168.1.4") as websocket:
            async for message in websocket:
                print(" dataGonder gelen:",gelen)
                self.responseMessage=gelen
                #self.messageGonder=1
                await websocket.send(gelen)


class Ui(QtWidgets.QMainWindow):
    def __init__(self):
        super(Ui, self).__init__()
        uic.loadUi('mainwindow.ui', self)
        self.th1_ws = SocketThread()
        self.th1_ws.ws_datalar_signal.connect(self.dataGuncelle)
        self.th1_ws.start()
        self.pb_out_1.clicked.connect(lambda: self.wsGonder('1'))
        self.pb_out_2.clicked.connect(lambda: self.wsGonder('2'))
        self.pb_out_3.clicked.connect(lambda: self.wsGonder('3'))
        self.pb_out_4.clicked.connect(lambda: self.wsGonder('4'))
        
        self.show()

    @pyqtSlot(object)    
    def dataGuncelle(self,datalar):
        print("datalar:",datalar)
       
        nereye=datalar['nereye']
        if nereye =="iolar":
            sensorData=datalar['sensorData']
            ctemp=datalar['ctemp']
            tarih=datalar['tarih']
            for i in range(1,5):
                exec(f"out{i}=datalar['out{i}']")
                exec(f"inp{i}=datalar['inp{i}']")
                kontrolOut=eval(f"out{i}=='1'")                
                if kontrolOut==True:
                    exec(f"self.pb_out_{i}.setStyleSheet('background-color: green;color:white;')")
                else:
                    exec(f"self.pb_out_{i}.setStyleSheet('background-color: red;color:white;')")
                
                kontrolIn=eval(f"inp{i}=='1'")
                if kontrolIn==True:
                    exec(f"self.lb_inp_{i}.setStyleSheet('background-color: green;color:white;')")
                else:
                    exec(f"self.lb_inp_{i}.setStyleSheet('background-color: red;color:white;')")
                
            self.lb_data_1.setText(str(sensorData))
            self.lb_data_2.setText(str(ctemp))
            self.lb_data_3.setText(str(tarih))

    def wsGonder(self,gelen):
        button = self.sender()
        button_name = button.text()
        palette = button.palette()
        background_color = palette.color(QPalette.Background)
        bgcolor=background_color.name()
        gonder=0
        
        if bgcolor=="#ff0000":
            gonder=1
        elif bgcolor=="#008000":
            gonder=0

        #print("tıklandı:",button_name," gelen:",gelen," background_color:",bgcolor)
        responseJson = {"nereye":"outespc","cihaz_id":1001,"out": f"out{gelen}","out_value":gonder,"gecikme":0}
        responseMessage = json.dumps(responseJson)

        asyncio.run(self.th1_ws.gelenData(responseMessage))


app = QtWidgets.QApplication(sys.argv)
window = Ui()
app.exec_()
