# Code pour gerer le reseau (la carte)
# Pour l'instant c'est juste un wrapper autour de sumolib
# mais si on se decide à utiliser notre propre format dans le futur ça facilitera la transition

import sumolib
from PySide6.QtGui import QPainter, QPolygonF
from PySide6.QtCore import Qt, QPointF, QThread

def safeCall(func):
    def inner(*args, **kwargs):
        if not args[0].isLoaded():
            return
        return func(*args, **kwargs)
    return inner
    


class Map:
    def __init__(self,path=None):
        if path is not None:
            self.fromPath(path)
        self.net = None
    
    def fromPath(self,path):
        self.net = sumolib.net.readNet(path,withInternal=True,withConnections=True)
   
    def isLoaded(self):
        return not (self.net is None)

    @safeCall
    def draw(self, painter):
        for edge in self.net.getEdges():
            color=Qt.white
            if(edge.getFunction()=="internal"):
                color=Qt.red
            painter.setPen(color)
            for lane in edge.getLanes():
                pts=[QPointF(*p) for p in lane.getShape()]
                poly = QPolygonF.fromList(pts)
                painter.drawPolyline(poly)
    
    @safeCall
    def getEdge(self,edgeID):
        return self.net.getEdge(edgeID)

    @safeCall
    def getNode(self,nodeID):
        return self.net.getNode(nodeID)
   
    @safeCall
    def getLane(self,laneID):
        return self.net.getLane(laneID)
    
    @safeCall
    def getBounds(self):
        return self.net.getBBoxXY()
    
    @safeCall
    def convertPos(self,pos):
        bounds=self.net.getBoundary()
        bounds[0]-=200
        bounds[1]-=0
        bounds[2]+=10
        bounds[3]+=0
        scale=min(self.surf.get_width()/(bounds[2]-bounds[0]),self.surf.get_height()/(bounds[3]-bounds[1]))
        
        x=pos[0]*scale-bounds[0]
        y=pos[1]*scale-bounds[1]
        
        return (x,self.surf.get_height()-y)
