from sqlalchemy.orm import Session

from errors.NotFoundException import NotFoundError
from modules.geoObjects import Driver, Track


class DriverHandler:
    dbSession: Session

    def __init__(self, session: Session):
        self.dbSession = session
        pass

    # handles creating a driver in the database
    def createDriver(self, name: str) -> Driver:
        try:
            # makes sure that a name always is provided
            if not name:
                raise ValueError("name is empty")

            driver = Driver(name=name)

            self.dbSession.add(driver)
            self.dbSession.commit()

            return driver
        except Exception as e:
            raise RuntimeError(f"failed to create driver with errors{e}")

    # handles getting a driver by its id from the database
    def getDriver(self, driverID: int) -> Driver:
        try:
            driver = self.dbSession.query(
                Driver).filter_by(id=driverID).first()
            if driver:
                return driver
            else:
                raise NotFoundError(
                    f"Driver with ID {driverID} not found", errors=[])
        except Exception as e:
            raise RuntimeError(f"failed to get driver with errors{e}")

    # handles getting all drivers from the database
    def getDrivers(self):
        try:
            drivers = self.dbSession.query(Driver).all()

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

            return driverList

        except Exception as e:
            raise RuntimeError(f"failed to get drivers with errors{e}")

    def deleteDriver(self, id):
        try:
            updated_rows = (
                self.dbSession.query(Track).filter(
                    Track.driver_id == id).update({Track.driver_id: 1})
            )
            self.dbSession.query(Driver).filter(Driver.id == id).delete()
            self.dbSession.commit()

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

