package org.academiadecodigo.bootcamp;

import org.academiadecodigo.bootcamp.car.Car;
import org.academiadecodigo.bootcamp.car.Tank;
import org.academiadecodigo.bootcamp.grid.position.GridPosition;

import java.util.ArrayList;

public class CollisionDetector {

    private Car[] cars;

    public CollisionDetector(Car[] cars) {
        this.cars = cars;
    }

    public ArrayList<Car> getCarsInSamePosition(GridPosition pos) {
        ArrayList<Car> crashed = new ArrayList<>();

        for (Car car : cars) {
            if (car.getPos() != pos && car.getPos().equals(pos) && car.isCrashed()) {
                crashed.add(car);
            }
        }

        return crashed;
    }

    public boolean isUnSafe(GridPosition pos) {

        for (Car c : cars) {

            if (c.getPos()!= pos && c.getPos().equals(pos)) {
                return true;
            }

        }

        return false;

    }

    /**
     * Checks for collisions with specific car
     * Requires iterating the array once
     * @param car
     */
    public void check(Collidable car) {

        for (Car ic : cars) {

            // No point in checking collisions with self
            if (ic == car) {
                continue;
            }

            if (ic.getPos().equals(car.getPos())) {
                ic.crash();
                car.crash();
            }
        }

    }

}
