from sqlalchemy.orm import Session

from modules.geoObjects import Track, Vehicle

class VehicleHandler:
    dbSession: Session
    
    def __init__(self, session:Session):
        self.dbSession = session
        pass
    
    # handles creating a vehicle and storing it in the database
    def createVehicle(self, name:str, licenseplate:str) -> Vehicle:
        if not name:
            raise ValueError("name is empty")
        
        vehicle = Vehicle(name=name, licenseplate=licenseplate)
        
        self.dbSession.add(vehicle)
        self.dbSession.commit()
        
        return vehicle
    
    # handles getting a vehicle identified with its id from the database
    def getVehicle(self, vehicleID:int) -> Vehicle:
        vehicle = self.dbSession.query(Vehicle).filter_by(id=vehicleID).first()
        
        return vehicle
    
    # handles getting all vehicles from database
    def getVehicles(self):
        vehicles = self.dbSession.query(Vehicle).all()

        driverList = [
            {
                "id": vehicle.id,
                "name": vehicle.name,
                "licensePlate": vehicle.licenseplate
            }
            # iterates all drivers and appends them to the list
            for vehicle in vehicles
        ]

        return driverList

    def deleteVehicle(self, id):
        try:
            updated_rows = (
                self.dbSession.query(Track).filter(
                    Track.vehicle_id == id).update({Track.vehicle_id: 1})
            )
            self.dbSession.query(Vehicle).filter(Vehicle.id == id).delete()
            self.dbSession.commit()

        except Exception as e:
            raise RuntimeError(f"failed to delete driver due to error: {e}")