package core.db.repositories;

import core.models.Car;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class CarRepository extends Repository<Car>
{
    public CarRepository() throws SQLException
    {
        super();
    }

    @Override
    public void save(Car car) throws SQLException
    {
        Statement statement = getStatement();

        String query = "INSERT INTO db.cars (name, type, color, volume) VALUES ('%s', '%s', '%s', '%s');";
        query = query.formatted(car.getName(), car.getType(), car.getColor(), car.getVolume());

        statement.executeUpdate(query);
    }

    @Override
    public Car get(int id) throws SQLException
    {
        Statement statement = getStatement();

        String query = "SELECT * FROM db.cars WHERE id = %d;".formatted(id);
        ResultSet result = statement.executeQuery(query);

        result.next();
        Car car = map(result);
        result.close();

        return car;
    }

    @Override
    public List<Car> get() throws SQLException
    {
        Statement statement = getStatement();

        String query = "SELECT * FROM db.cars;";
        ResultSet result = statement.executeQuery(query);

        List<Car> cars = maps(result);
        result.close();

        return cars;
    }

    private Car map(ResultSet result) throws SQLException
    {
        return new Car(
                result.getInt("id"),
                result.getString("name"),
                result.getString("type"),
                result.getString("color"),
                result.getFloat("volume")
        );
    }

    private List<Car> maps(ResultSet result) throws SQLException
    {
        List<Car> cars = new ArrayList<Car>();

        while (result.next())
        {
            cars.add(map(result));
        }

        return cars;
    }
}
