import os, sys
if 'SUMO_HOME' in os.environ:
    tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
    sys.path.append(tools)
else:
    print("please declare environment variable 'SUMO_HOME'")

from PySide6.QtCore import Qt, QTimer, QElapsedTimer, QThread, Slot, Signal
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QFileDialog
from PySide6.QtGui import QSurfaceFormat, QAction
from window import Ui_MainWindow

from mainLoop import mainLoop

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setFocus()

        self.updateThread = QThread()

        self.mainLoop = mainLoop(self)

        self.mainLoop.moveToThread(self.updateThread)
        self.updateThread.started.connect(self.mainLoop.start)
        self.updateThread.start()

        fileMenu = self.menuBar().addMenu("&File")
        openMenu = fileMenu.addMenu("&Open")

        openNet = QAction("&Open Network",self)
        openNet.setStatusTip("Open Network file (.net.xml)")
        openNet.triggered.connect(self.openNetwork)
        openMenu.addAction(openNet)

        openVeh = QAction("&Open Vehicles",self)
        openVeh.setStatusTip("Open Vehicle description (.rou.xml)")
        openVeh.triggered.connect(self.openVehicles)
        openMenu.addAction(openVeh)

        self.drawTimer = QTimer(self)
        self.drawTimer.timeout.connect(self.ui.mainSurf.update)
        self.drawTimer.timeout.connect(self.updateFPS)
        self.drawTimer.start(1000/60)

        self.ui.startButton.clicked.connect(self.mainLoop.timer.start)
        self.ui.stopButton.clicked.connect(self.mainLoop.timer.stop)

        self.ui.mainFPS_set.valueChanged.connect(self.drawTimer.setInterval)
        self.ui.physicsFPS_set.valueChanged.connect(self.mainLoop.timer.setInterval)

        self.fpsTimer = QElapsedTimer()
        self.fpsTimer.start()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape or e.key() == Qt.Key_Q:
            self.close()

        elif e.key() == Qt.Key_S:
            self.mainLoop.quickLoad()

    def updateFPS(self):
        widget = self.findChild(QLabel,"mainFps")
        t = self.fpsTimer.restart()
        if(t == 0):
            return
        widget.setText(f"fps : {1000/t:.1f}")
        widget.update()

    @Slot(int)
    def updatePhysicsFps(self,t):
        widget = self.findChild(QLabel,"physicsFPS")
        if(t == 0):
            return
        widget.setText(f"ph fps : {1000/t:.1f}")

    def openNetwork(self):
        filename = QFileDialog.getOpenFileName(self,"Open Network", "./", "Network File (*.net.xml)")
        self.mainLoop.openNetwork(filename[0])

    def openVehicles(self):
        filename = QFileDialog.getOpenFileName(self,"Open Vehicle trip description", "./", "Route File (*.rou.xml)")
        self.mainLoop.openVehicles(filename[0])

    def close(self):
        self.updateThread.quit()
        self.updateThread.wait()
        super().close()



if __name__ == "__main__":
    app = QApplication()

    f = QSurfaceFormat()
    f.setDepthBufferSize(24)
    f.setVersion(3, 2)
    f.setSamples(4)
    f.setProfile(QSurfaceFormat.CoreProfile)
    QSurfaceFormat.setDefaultFormat(f)

    window = MainWindow()
    window.show()

    sys.exit(app.exec())
