package javalabs.lab4.first;

import java.util.Arrays;

public class Garage {
    private Vehicle[] _vehicles;

    public Garage() {
        _vehicles = new Vehicle[0];
    }

    public Garage(Vehicle[] vehicles) {
        _vehicles = vehicles != null ? vehicles : new Vehicle[0];
    }

    public Vehicle[] getVehicles() { return _vehicles; }
    public void setVehicles(Vehicle[] vehicles) {
        _vehicles = vehicles != null ? vehicles : new Vehicle[0];
    }

    public Vehicle getVehicle(int index) {
        if (index >= 0 && index < _vehicles.length) {
            return _vehicles[index];
        }
        return null;
    }
    public void setVehicle(int index, Vehicle vehicle) {
        if (index >= 0 && index < _vehicles.length && vehicle != null) {
            _vehicles[index] = vehicle;
        }
    }

    public boolean addVehicle(Vehicle vehicle) {
        if (vehicle != null) {
            Vehicle[] newVehicles = Arrays.copyOf(_vehicles, _vehicles.length + 1);
            newVehicles[newVehicles.length - 1] = vehicle;
            _vehicles = newVehicles;
            return true;
        }
        return false;
    }

    public Vehicle popVehicle() {
        if (_vehicles.length > 0) {
            Vehicle[] newVehicles = Arrays.copyOf(_vehicles, _vehicles.length - 1);
            Vehicle vehicleToReturn = _vehicles[_vehicles.length - 1];
            _vehicles = newVehicles;
            return vehicleToReturn;
        }
        return null;
    }

    public void count() {
        int carCount = 0;
        int bikeCount = 0;
        int truckCount = 0;
        int otherCount = 0;
        for (Vehicle vehicle : _vehicles) {
            if (vehicle instanceof Car) carCount++;
            else if (vehicle instanceof Bike) bikeCount++;
            else if (vehicle instanceof Truck) truckCount++;
            else otherCount++;
        }

        System.out.printf("{\"Garage\": {\"Cars\": %d, \"Bikes\": %d, \"Trucks\": %d, \"Others\": %d}}\n",
                carCount, bikeCount, truckCount, otherCount);
    }

    public void setVehicleVelocity(int index, int velocity) {
        if (index >= 0 && index < _vehicles.length)
            _vehicles[index].setVelocity(velocity);
    }

    @Override
    public String toString() {
        String result = "{\"" + this.getClass().getSimpleName()
                + "\": {\"size\":" + _vehicles.length
                + ", \"vehicles\": [";
        for (Vehicle vehicle : _vehicles) {
            result += vehicle.toString() + ",";
        }
        result = result.substring(0, result.length() - 1) + "]}}";
        return result;
    }
}