package org.academiadecodigo.bootcamp;

import org.academiadecodigo.bootcamp.car.Car;
import org.academiadecodigo.bootcamp.car.CarFactory;
import org.academiadecodigo.bootcamp.car.Human;
import org.academiadecodigo.bootcamp.grid.Grid;
import org.academiadecodigo.bootcamp.grid.GridFactory;
import org.academiadecodigo.bootcamp.grid.GridType;

import java.util.ArrayList;

/**
 * The game logic
 */
public class Game {


    /**
     * Graphical Car field
     */
    private Grid grid;

    /**
     * Container of Cars
     */
    private Car[] cars;

    private ArrayList<Bullet> bullets = new ArrayList<>();

    /**
     * Animation delay
     */
    private int delay;

    /**
     * The collision detector
     */
    private CollisionDetector collisionDetector;

    private Handler keyHandler;

    /**
     * Number of cars to manufacture
     */
    private int manufacturedCars = 20;

    /**
     * Constructs a new game
     * @param gridType which grid type to use
     * @param cols number of columns in the grid
     * @param rows number of rows in the grid
     * @param delay animation delay
     */
    Game(GridType gridType, int cols, int rows, int delay) {

        grid = GridFactory.makeGrid(gridType, cols, rows);
        this.delay = delay;

    }

    /**
     * Creates a bunch of cars and randomly puts them in the field
     */
    public void init() {

        grid.init();

        cars = new Car[manufacturedCars];
        collisionDetector = new CollisionDetector(cars);

//        cars[0] = new Human(grid.makeGridPosition());
//        cars[0].setCollisionDetector(collisionDetector);
//        cars[0].setGrid(grid);
//
//        cars[1] = new Human(grid.makeGridPosition());
//        cars[1].setCollisionDetector(collisionDetector);
//        cars[1].setGrid(grid);
//
//        keyHandler = new Handler(cars[0], cars[1]);

        for (int i = 0; i < manufacturedCars; i++) {

            cars[i] = CarFactory.getNewCar(grid);
            cars[i].setCollisionDetector(collisionDetector);
            cars[i].setGrid(grid);

        }
    }

    /**
     * Starts the animation
     *
     * @throws InterruptedException
     */
    public void start() throws InterruptedException {

        while (true) {

            // Pause for a while
            Thread.sleep(delay);

            moveAllCars();

            moveBullets();

        }

    }

    /**
     * Moves all cars
     */
    public void moveAllCars() {
        for (Car c : cars) {
            c.move();
            collisionDetector.check(c);
        }

    }

    public void moveBullets() {
        if (bullets.isEmpty()) { return; }
        for (Bullet bullet : bullets) {
            bullet.move();
            collisionDetector.check(bullet);
        }
    }

}
