from PySide6.QtOpenGLWidgets import QOpenGLWidget
from PySide6.QtCore import Qt, QThread
from PySide6.QtGui import QPainter, QFont, QColor, QTransform, QOpenGLContext, QOpenGLFunctions
from PySide6 import QtOpenGL

class mainPainter(QOpenGLWidget):
    def __init__(self, parent=None):
        super(mainPainter, self).__init__(parent)
         
        self.map = None
        self.carController = None
        self.transform = QTransform()
    
    def addMap(self, netMap):
        self.map = netMap

    def addCarController(self, cc):
        self.carController = cc

    def generateTransform(self):
        bounds = self.map.getBounds()
        if(bounds is None):
            return
        bounds[0] = list(map(lambda b: b-10,bounds[0]))
        bounds[1] = list(map(lambda b: b+10, bounds[1]))
        self.transform.reset()
        tr = QTransform()
        tr.translate(-bounds[0][0],-bounds[0][1])
        scale=min(self.width()/(bounds[1][0]-bounds[0][0]),self.height()/(bounds[1][1]-bounds[0][1]))
        sc = QTransform()
        sc.scale(scale,-scale)
        self.transform = tr * sc * QTransform(1, 0, 0, 1, 0, self.height())

    def resizeGL(self,w,h):
        self.generateTransform()

    def paintEvent(self, e):
        painter = QPainter(self)
        painter.RenderHint(QPainter.Antialiasing)
        painter.eraseRect(e.rect());
        painter.setTransform(self.transform)
        self.map.draw(painter)
        self.carController.draw(painter)
