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

# Form implementation generated from reading ui file 'camera_val.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# 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.

import threading
import queue
import time
import os
import subprocess
from PyQt5 import QtCore, QtGui, QtWidgets
from launcher import Ui_MainWindow
#from launcher import Ui_Dialog




TIME_LIMIT = 100
CLOSE_EVENT = 'close'
class NotifyThread(QtCore.QThread):
    signal_to_Gui  = QtCore.pyqtSignal(object)
    signal_to_Thread = QtCore.pyqtSignal(object)
    signal_to_Window = QtCore.pyqtSignal(object)
    signal_between_Windows = QtCore.pyqtSignal(object)

class FunctionThread(QtCore.QThread):
    def __init__(self, emitThread):
        super(FunctionThread, self).__init__()
        self.emitThread=emitThread
        self.emitThread.signal_to_Thread.connect(self.signalHook)
        self.running=True
    def signalHook(self,item):
        if item == CLOSE_EVENT:
            self.running = False
    

class TimerThread(FunctionThread):
    def __init__(self, emitThread):
        super(TimerThread, self).__init__(emitThread)
    def run(self):                
        #print("Start emit thread")
        count = 0
        while count < TIME_LIMIT and self.running:
            count +=1
            print("in TimerThread", count)
            time.sleep(0.13)
            self.emitThread.signal_to_Gui.emit(1)
            
TASK_ONE_MILESTONE= 70
TASK_TWO_MILESTONE= 90

class JobThread(FunctionThread):
    def __init__(self, emitThread):
        super(JobThread, self).__init__(emitThread)
    def run(self):                
        #print("Start emit thread")
        count = 0
        time.sleep(0.1)
        while True:
            self.emitThread.signal_to_Gui.emit(['Upgrading...\r\n',0])
            upgrade=subprocess.check_output(['sudo','pip3','install','spotii','-U']).decode("utf-8")
            self.emitThread.signal_to_Gui.emit([upgrade,TASK_ONE_MILESTONE])

            if not self.running:
                break;
            self.emitThread.signal_to_Gui.emit(['Initializing...\r\n',TASK_ONE_MILESTONE+1])
#             location = subprocess.check_output(['pip3','show','spotii']).decode("utf-8")
#             print(location)
#             location='/usr/local/lib'+location.split('/usr/local/lib')[-1].split('\n')[0]
#             print(location)
#             self.emitThread.signal_to_Window.emit(location)
            self.emitThread.signal_to_Gui.emit(['Starting...\r\n',TASK_TWO_MILESTONE])
            break;
            
        

            
class MyUi(Ui_MainWindow):
    def __init__(self, emitThread):
        super(MyUi, self).__init__()
        self.emitThread=emitThread
        self.emitThread.signal_to_Gui.connect(self.emitHook)
        self.count=0
 
    def setupParts(self):
        pass


    def emitHook(self,item):
        try:
            if type(item) == int:
                if item != TASK_ONE_MILESTONE -1 :
                    self.count+=item
            else:
                self.count=item[1]
                self.label.setText(self.label.text()+item[0])
            self.progressBar.setProperty("value", self.count)
            if self.count == 100:
                self.emitThread.signal_to_Window.emit(CLOSE_EVENT)
        except Exception as e:
            print(e)
        
class MyMainWindow(QtWidgets.QMainWindow):
#class MyMainWindow(QtWidgets.QDialog):
#     def __init__(self,parent=None,emitThread):
#         super(MyMainWindow, self).__init__(parent)
    def __init__(self,emitThread):
        super(MyMainWindow, self).__init__()
        
        self.initDone=False
#        self.emitThread=EmitThread()
        self.emitThread=emitThread
        self.emitThread.signal_to_Window.connect(self.windowSignalHook)
        self.emitThread.signal_between_Windows.connect(self.fromOtherWindow)

        self.timerThread=TimerThread(self.emitThread)
        self.timerThread.start()

        self.jobThread=JobThread(self.emitThread)
        self.jobThread.start()

    def windowSignalHook(self, item):
        print(item)
        if item ==CLOSE_EVENT:
            self.emitThread.signal_to_Thread.emit(CLOSE_EVENT)
            
            QtWidgets.qApp.quit()
            #time.sleep(1.5)
            self.initDone=True
            #self.close()
            
    def fromOtherWindow(self, item):
        print(item)
        if item =='appReady':
            self.close()
            
        
    
    def closeEvent(self,event):
        print("main window is closing")
        self.emitThread.signal_to_Thread.emit(CLOSE_EVENT)
        #self.emitThread.join()
        print("everthing done")
        
        #exit(-1)
    def status(self):
        return self.initDone
        

if __name__ == "__main__":
    import sys
    emitThread=NotifyThread()
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = MyMainWindow(emitThread) ##QtWidgets.QMainWindow()
    ui = MyUi(emitThread)
    ui.setupUi(MainWindow)
    ui.setupParts()

    
    MainWindow.show()
    returnValue =app.exec_()
    print('launcher return value :' ,returnValue)
    initialized = MainWindow.status()
    if returnValue == 0 and initialized:
        
        from spotii import spot_main
        spot_main(emitThread)
        
    else:
        sys.exit(0)
