from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QObject, QThread, pyqtSignal
import time
from firstversion import *
import lcm
from exlcm import structure
from PyQt5.QtWidgets import QApplication

global check


class mainProgram(Ui_MainWindow):
    check = False

    def __init__(self, parent=None):
        Ui_MainWindow.__init__(self)
        self.setupUi(MainWindow)
        self.start_b.clicked.connect(self.start)
        self.stop_b.clicked.connect(self.stop)
        self.estop_b.clicked.connect(self.estop)

    def my_handler(self, channel, data):
        self.thread=QThread()
        self.lcmClass=lcmClass()
        self.lcmClass.moveToThread(self.thread)  
        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.progress.connect(self.reportProgress)
        # Step 6: Start the thread
        self.thread.start()        
        msg = structure.decode(data)
        dist= str(msg.dist)
        pres= str(msg.pres)
        print(dist)
        self.dist_t.setText(dist)
        self.dist_t.repaint()


    def start(self):
        check = True
        self.state_t.setText("Active")
        self.state_t.setAlignment(QtCore.Qt.AlignCenter)
        self.dist_t.repaint()
        self.lcm_func(check)

    def stop(self):
        check= False
        self.dist_t.setText("0")
        self.state_t.setText("STOPPING")
        self.state_t.setAlignment(QtCore.Qt.AlignCenter)
        self.state_t.repaint()
        time.sleep(2)
        self.state_t.setText("GROUND")
        self.state_t.setAlignment(QtCore.Qt.AlignCenter)
 

    def estop(self):
        check = False
        self.state_t.setText("GROUND")
        self.state_t.setAlignment(QtCore.Qt.AlignCenter)

class lcmClass(QObject,Ui_MainWindow):
    def lcm_func(self, lcmState):
        finished = pyqtSignal()
        progress = pyqtSignal(int)
        lc= lcm.LCM()
        subscription= lc.subscribe("NIRMAAN", self.my_handler)
        try:
            while(lcmState):
                lc.handle()
            lc.unsubscribe()
        except KeyboardInterrupt:
            pass


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    # ui = Ui_MainWindow()
    ui=lcmClass()
    ui.setupUi(MainWindow)
    m1= mainProgram()
    MainWindow.show()
    sys.exit(app.exec_())