import sys

from Map import Map
from CarController import CarController

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

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

        self.map = Map()

        self.controller = CarController(self.map, parent)

        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)

        self.fpsAverage = 0
    
    def threadSafe(func):
        def inner(*args, **kwargs):
            args[0].mutex.lock()
            func(*args, **kwargs)
            args[0].mutex.unlock()
        return inner

    def start(self):
        self.fpsTimer.start()
        self.stopSignal.connect(self.timer.stop)

    @threadSafe
    def update(self):
        try:
            self.controller.update()
        except:
            (type, value, traceback) = sys.exc_info()
            print(type, value, traceback)
    
    @threadSafe
    def openNetwork(self, filename):
        if filename == '':
            return
        self.map.fromPath(filename)
        self.painter.generateTransform()

        self.controller.prepareRoute()

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

    def updateFps(self):
        self.fpsAverage += 1
        if(self.fpsAverage == 32):
            newFps = self.fpsTimer.restart()
            self.updateFPS.emit(newFps/32)
            self.fpsAverage = 0

