from Map import Map
from CarController import CarController

from PySide6.QtWidgets import QFileDialog, QToolBox
from PySide6.QtCore import QElapsedTimer, QTimer, QElapsedTimer, QObject, Signal, Slot

class mainLoop(QObject):
    updateFPS = Signal(int)
    def __init__(self, parent):
        super().__init__()
        self.parent = parent
        self.painter = parent.ui.mainSurf

        self.map = Map()

        self.controller = CarController(self.map)

        self.controller.setInfoWidget(parent.findChild(QToolBox,"carInfos"))

        self.painter.addMap(self.map)
        self.painter.addCarController(self.controller)
        
        self.timer = QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.timeout.connect(self.updateFps)
        self.timer.setInterval(1000/60)

        self.fpsTimer = QElapsedTimer()
        self.updateFPS.connect(self.parent.updatePhysicsFps)
    
    def start(self):
        self.fpsTimer.start()

    def update(self):
        self.controller.update()

    def openNetwork(self, filename):
        if filename == '':
            return
        self.map.fromPath(filename)
        self.painter.generateTransform()

        self.controller.prepareRoute()

    def openVehicles(self, filename):
        if filename == '':
            return
        self.controller.fromPath(filename)
        if self.map.isLoaded():
            self.controller.prepareRoute()
    
    def quickLoad(self):
        self.map.fromPath("test2.net.xml")
        self.painter.generateTransform()
        self.controller.fromPath("test5.rou.xml")
        self.controller.prepareRoute()

    def updateFps(self):
        newFps = self.fpsTimer.restart()
        self.updateFPS.emit(newFps)

