# -*- coding: utf-8 -*-


# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.
# I kinda know what i am doing
#Autor:      Andre Coladello / Lucas Ryu / Victor Daisuke

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QObject, QThread, pyqtSignal
import sys
import socket as SOCKET
from threading import Thread

class SetupWindow(QtWidgets.QMainWindow):

        def __init__(self):
                super().__init__()
                self.IP_hostValue = '192.168.137.1'
                self.PortSendValue = '23'
                self.PortRecvValue = '1234'

                self.setupUi(self)

        def setupUi(self, MainWindow):
                MainWindow.setObjectName("MainWindow")
                MainWindow.resize(550, 550)
                self.centralwidget = QtWidgets.QWidget(MainWindow)
                self.centralwidget.setObjectName("centralwidget")
                self.Input_IP = QtWidgets.QPlainTextEdit(self.centralwidget)
                self.Input_IP.setGeometry(QtCore.QRect(60, 120, 311, 31))
                self.Input_IP.setObjectName("Input_IP")
                self.PortSend = QtWidgets.QPlainTextEdit(self.centralwidget)
                self.PortSend.setGeometry(QtCore.QRect(60, 240, 311, 31))
                self.PortSend.setObjectName("PortSend")
                self.PortReceive = QtWidgets.QPlainTextEdit(self.centralwidget)
                self.PortReceive.setGeometry(QtCore.QRect(60, 310, 311, 31))
                self.PortReceive.setObjectName("PortReceive")
                self.label = QtWidgets.QLabel(self.centralwidget)
                self.label.setGeometry(QtCore.QRect(60, 100, 71, 16))
                self.label.setObjectName("label")
                self.label_2 = QtWidgets.QLabel(self.centralwidget)
                self.label_2.setGeometry(QtCore.QRect(60, 220, 241, 16))
                self.label_2.setObjectName("label_2")
                self.label_3 = QtWidgets.QLabel(self.centralwidget)
                self.label_3.setGeometry(QtCore.QRect(60, 290, 311, 16))
                self.label_3.setObjectName("label_3")
                self.connect_button = QtWidgets.QPushButton(self.centralwidget)
                self.connect_button.setGeometry(QtCore.QRect(190, 360, 181, 25))
                self.connect_button.setObjectName("connect_button")
                MainWindow.setCentralWidget(self.centralwidget)
                self.menubar = QtWidgets.QMenuBar(MainWindow)
                self.menubar.setGeometry(QtCore.QRect(0, 0, 550, 25))
                self.menubar.setObjectName("menubar")
                MainWindow.setMenuBar(self.menubar)
                self.statusbar = QtWidgets.QStatusBar(MainWindow)
                self.statusbar.setObjectName("statusbar")
                MainWindow.setStatusBar(self.statusbar)

                #Modificado
                MainWindow.setStyleSheet("background-image:url(./icons/interface_0.png)")
                self.connect_button.clicked.connect(self.startServer)  # runs the method
                self.Input_IP.setPlainText(self.IP_hostValue)
                self.PortSend.setPlainText(self.PortSendValue)
                self.PortReceive.setPlainText(self.PortRecvValue)

                self.retranslateUi(MainWindow)
                QtCore.QMetaObject.connectSlotsByName(MainWindow)

        def retranslateUi(self, MainWindow):
                _translate = QtCore.QCoreApplication.translate
                MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
                self.label.setText(_translate("MainWindow", "Insira o IP:"))
                self.label_2.setText(_translate("MainWindow", "Insira a porta para envio de mensagens:"))
                self.label_3.setText(_translate("MainWindow", "Insira a porta para o recebimento de mensagens:"))
                self.connect_button.setText(_translate("MainWindow", "Connect!"))

        def startServer(self):
                input_IP = self.Input_IP.toPlainText().strip()
                portSend = self.PortSend.toPlainText().strip()
                portReceive = self.PortReceive.toPlainText().strip()
                self.main_window = Ui_MainWindow(input_IP, int(portSend), int(portReceive))


class Ui_MainWindow(QtWidgets.QMainWindow):
        def __init__(self, ip_host: str, portSend: int, portRecv: int):
                self.ip_host = ip_host
                self.portSend = portSend
                self.portRecv = portRecv
                super().__init__()
                self.PortServSend = Server_Functions(self.ip_host,self.portSend)
                self.setupUi(self)

        def setupUi(self, MainWindow):
                MainWindow.setObjectName("MainWindow")
                MainWindow.resize(550, 550)

                self.centralwidget = QtWidgets.QWidget(MainWindow)
                self.centralwidget.setObjectName("centralwidget")
                self.left_button = QtWidgets.QPushButton(self.centralwidget)
                self.left_button.setGeometry(QtCore.QRect(50, 230, 71, 101))
                self.left_button.setStyleSheet("#left_button{\n"
                "background-color: transparent;\n"
                "border-image: url(./icons/left_button_normal.png);\n"
                "background: none;\n"
                "border: none;\n"
                "background-repeat: none;\n"
                "}\n"
                "#left_button:pressed\n"
                "{\n"
                "   border-image: url(./icons/left_button_pressed.png);\n"
                "}")
                self.left_button.setText("")
                self.left_button.setObjectName("left_button")
                self.right_button = QtWidgets.QPushButton(self.centralwidget)
                self.right_button.setGeometry(QtCore.QRect(240, 270, 51, 101))
                self.right_button.setStyleSheet("#right_button{\n"
                "background-color: transparent;\n"
                "border-image: url(./icons/right_button_normal.png);\n"
                "background: none;\n"
                "border: none;\n"
                "background-repeat: none;\n"
                "}\n"
                "#right_button:pressed\n"
                "{\n"
                "   border-image: url(./icons/right_button_pressed.png);\n"
                "}")
                self.right_button.setText("")
                self.right_button.setObjectName("right_button")
                self.spin = QtWidgets.QSpinBox(self.centralwidget)
                self.spin.setGeometry(QtCore.QRect(370, 150, 81, 41))
                self.spin.setStyleSheet("#spin{\n"
                "    font: 75 12pt \"MS Shell Dlg 2\";\n"
                "    text-color: darkblue;\n"
                "}")
                self.spin.setMinimum(0)
                self.spin.setMaximum(180)
                self.spin.setSingleStep(30)
                self.spin.setObjectName("spin")
                self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)
                self.textBrowser.setGeometry(QtCore.QRect(20, 20, 511, 50))
                self.textBrowser.setStyleSheet("#textBrowser{background-color: transparent;}")
                self.textBrowser.setObjectName("textBrowser")
                self.LCD1 = QtWidgets.QLCDNumber(self.centralwidget)
                self.LCD1.setGeometry(QtCore.QRect(360, 310, 101, 41))
                self.LCD1.setObjectName("LCD1")
                self.LCD2 = QtWidgets.QLCDNumber(self.centralwidget)
                self.LCD2.setGeometry(QtCore.QRect(360, 410, 101, 41))
                self.LCD2.setObjectName("LCD2")
                self.label = QtWidgets.QLabel(self.centralwidget)
                self.label.setGeometry(QtCore.QRect(370, 290, 91, 16))
                self.label.setObjectName("label")
                self.label_2 = QtWidgets.QLabel(self.centralwidget)
                self.label_2.setGeometry(QtCore.QRect(380, 390, 71, 16))
                self.label_2.setObjectName("label_2")
                MainWindow.setCentralWidget(self.centralwidget)
                self.menubar = QtWidgets.QMenuBar(MainWindow)
                self.menubar.setGeometry(QtCore.QRect(0, 0, 550, 25))
                self.menubar.setObjectName("menubar")
                self.menuControle_de_Motores = QtWidgets.QMenu(self.menubar)
                self.menuControle_de_Motores.setObjectName("menuControle_de_Motores")
                MainWindow.setMenuBar(self.menubar)
                self.statusbar = QtWidgets.QStatusBar(MainWindow)
                self.statusbar.setObjectName("statusbar")
                MainWindow.setStatusBar(self.statusbar)
                self.menubar.addAction(self.menuControle_de_Motores.menuAction())

                #Modificado após a conversão
                self.left_button.clicked.connect(self.left_btn_click)  # runs the method
                self.right_button.clicked.connect(self.right_btn_click)  # runs the method
                MainWindow.setStyleSheet("background-image:url(./icons/interface_1.png)")

                self.startThread()

                self.retranslateUi(MainWindow)

                QtCore.QMetaObject.connectSlotsByName(MainWindow)
                self.show()



        def retranslateUi(self, MainWindow):
                _translate = QtCore.QCoreApplication.translate
                MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
                self.textBrowser.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:7.8pt; font-weight:400; font-style:normal;\">\n"
                "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:11pt; font-weight:600; color:#ffffff;\">Selecione o deslocamento, e clique na seta para enviar.</span></p></body></html>"))
                self.label.setText(_translate("MainWindow", "Posição Atual"))
                self.label_2.setText(_translate("MainWindow", "Velocidade"))
                self.menuControle_de_Motores.setTitle(_translate("MainWindow", "Controle de Motores"))
        
        def left_btn_click(self):
                Numb = self.spin.value()
                self.PortServSend.send_message('E '+ str(Numb) +'\n')
                self.spin.setValue(0)

        def right_btn_click(self):
                Numb = self.spin.value()
                self.PortServSend.send_message('D '+ str(Numb) +'\n')
                self.spin.setValue(0)

        def attLCD1(self, nPosValue):
                #print('Valor Recebido P ' + str(nPosValue))
                self.LCD1.display(nPosValue)

        def attLCD2(self, nVelValue):
                #print('Valor Recebido V ' + str(nVelValue))
                self.LCD2.display(nVelValue)

        def startThread(self):
                # Step 2: Create a QThread object
                self.thread = QThread()
                # Step 3: Create a worker object
                self.worker = RecevServer(self.ip_host,self.portRecv)
                # Step 4: Move worker to the thread
                self.worker.moveToThread(self.thread)
                # Step 5: Connect signals and slots
                self.thread.started.connect(self.worker.run)
                self.worker.finished.connect(self.thread.quit)
                self.worker.finished.connect(self.worker.deleteLater)
                self.thread.finished.connect(self.thread.deleteLater)
                self.worker.LCD1.connect(self.attLCD1)
                self.worker.LCD2.connect(self.attLCD2)
                # Step 6: Start the thread
                self.thread.start()

class RecevServer(QtCore.QObject):
        finished = pyqtSignal()
        LCD1 = pyqtSignal(int) #posicao
        LCD2 = pyqtSignal(int) #velocidade

        def __init__(self, ip_host: str, portRecv: int):
                super().__init__()
                self.ip_host = ip_host
                self.portRecv = portRecv
                self.flag = True

        def run(self):
                """Conteudo da Thread"""
                self.RecvServPort = Server_Functions(self.ip_host,self.portRecv)
                while self.flag:
                        try:
                                msg = self.RecvServPort.recv_message().split('-') #Cria uma array com as mensagens
                                #print(msg)
                                if msg[0] == 'P':
                                        #print('Dentro do P')
                                        self.LCD1.emit(int(msg[1]))
                                else:
                                        #print('Dentro do V')
                                        self.LCD2.emit(int(msg[1]))
                                #self.RecvServPort.send_message('Enviando')
                        except Exception as e:
                                print('Erro ao receber mensagens: ' + str(e))
                                self.finished.emit()
                                self.raise_exception()
                                break

        def raise_exception(self):
                        self.flag = False

class Server_Functions():
        def __init__(self, ip_host: str, port: int):
                self.start_server(ip_host, port)

        def start_server(self, ip_host: str, port: int):
                """
                Função responsável por estabelecer a conexão, disponibilizando o socket para todo o objeto
                """
                with SOCKET.socket(SOCKET.AF_INET, SOCKET.SOCK_STREAM) as s:
                        s.bind((ip_host, port))
                        print('listening...')
                        s.listen()
                        self.socket, addr = s.accept()
                        print('Conectado de: ' + str(addr))

        def send_message(self, msg: str):
                try:
                        self.socket.sendall(msg.encode()) #enviar a string message
                except:
                        print('não foi possível enviar a mensagem')

        def recv_message(self):
                return self.socket.recv(1024).decode('UTF-8')


if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
        main_window = SetupWindow()
        main_window.show()
        sys.exit(app.exec_())
