import sumolib
from Car import Car
from carInfo import Ui_carInfo
from PySide6.QtWidgets import QWidget, QLabel
from PySide6.QtCore import Qt, Slot, Signal, QThread
from PySide6.QtCharts import QChart, QSplineSeries, QLineSeries
from math import ceil

class carInfo(QWidget):
    def __init__(self,parent):
        super().__init__()
        self.ui = Ui_carInfo()
        self.ui.setupUi(self)
        self.maxV = 0
        self.parent = parent

        self.chart = self.ui.speedGraph.chart()
        #self.chart.setAnimationOptions(QChart.AllAnimations)

        speedsNames = ["vmax","vsec","Vitesse (m.s^-1)"]
        self.speedSeries = []
        for ind,s in enumerate(speedsNames):
            self.speedSeries.append(QLineSeries())
            self.speedSeries[ind].setName(s)
            # self.speedSeries[ind].setPointsVisible()
            self.chart.addSeries(self.speedSeries[ind])
        self.chart.createDefaultAxes()
    
    @Slot(tuple)
    def addSpeedPoint(self,params):
        ind=params[0]
        if self.parent.currentWidget() != self:
            return
        t=params[1]
        val=params[2]
        if(self.speedSeries[ind].count()>1 and self.speedSeries[ind].at(1).x()<t-500):
            self.speedSeries[ind].remove(0)
        self.speedSeries[ind].append(t,val)

        if self.speedSeries[ind].count()>2:
            i = self.speedSeries[ind].count()-1
            pm2 = self.speedSeries[ind].at(i-2)
            pm1 = self.speedSeries[ind].at(i-1)
            pm0 = self.speedSeries[ind].at(i)
            diffL = (pm1.y() - pm2.y())/(pm1.x() - pm2.x())
            diffR = (pm0.y() - pm1.y())/(pm0.x() - pm1.x())
            diff2 = diffR - diffL
            if diff2 == 0:
                self.speedSeries[ind].remove(i-1)

        xAxis = self.chart.axes(Qt.Horizontal,self.speedSeries[ind])[0]
        xAxis.setRange(max(t-500,0),t)

        if val>self.maxV:
            self.maxV = val
            yAxis = self.chart.axes(Qt.Vertical, self.speedSeries[ind])[0]
            yAxis.setMax(ceil(val+1))

        self.ui.speedGraph.update()
    
    @Slot(tuple)
    def setVal(self,params):
        key = params[0]
        val = params[1]
        obj = self.findChild(QLabel,key)
        if obj is None:
            return
        obj.setText(f"{key} : {val}")
        obj.update()

class CarController:
    def __init__(self,parentMap):
        self.map=parentMap
        self.cars=[]
        self.t=0
        self.infoWidget=None

    def fromPath(self,path):
        self.cars=[]
        self.t=0
        while self.infoWidget.count() != 0:
            self.infoWidget.removeItem(0)

        for vehicle in sumolib.xml.parse(path,"vehicle"):
            route=vehicle.route[0].edges.split()
            wId=self.infoWidget.addItem(carInfo(self.infoWidget), vehicle.id)
            self.cars.append(Car(vehicle.id,route,self.map,self,self.infoWidget.widget(wId)))

    def prepareRoute(self):
        for car in self.cars:
            car.prepareRoute()

    def getCarsOnEdge(self,edgeID):
        return filter(lambda c: c.route[c.index].getID()==edgeID,self.cars)

    def getCarsOnLane(self,edgeID,laneID):
        cars = self.getCarsOnEdge(edgeID)
        return cars #filter(lambda c: c.laneId == laneID,cars)

    def update(self):
        if self.map.net is None:
            return
        self.t+=1
        for car in self.cars:
            car.update(1.0/60)

    def draw(self,painter):
        for ind,car in enumerate(self.cars):
            selectedId = self.infoWidget.currentIndex()
            selectedCar = self.cars[selectedId]
            if ind == selectedId:
                painter.setPen(Qt.green)
            elif(selectedCar.leader is not None and selectedCar.leader.id == car.id):
                painter.setPen(Qt.red)
            else:
                painter.setPen(Qt.white)
            car.draw(painter)

    def setInfoWidget(self, widget):
        self.infoWidget = widget
