package UE21_290425_Bruecke;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Guard extends Thread {
    private static int carsOnBridge = 0;
    public final List<Car> waitingCars = new ArrayList<>();
    public final Set<Integer> waitingTimes = new HashSet<>();

    public synchronized void leaving() {
        carsOnBridge--;
    }

    public synchronized void arriving(Car car) {
        this.waitingCars.add(car);
        notify(); // Weckt den Guard auf
    }


    public synchronized void crossing(Car car) {
        carsOnBridge++;
        this.waitingCars.remove(car);
        car.start();
    }

    @Override
    public synchronized String toString() {
        StringBuilder output = new StringBuilder("Cars waiting:\n");
        if (waitingCars.isEmpty()) output = new StringBuilder("No Cars waiting:");
        for (Car car : waitingCars)
            output.append(String.format("Car%d:\t%02d:%02d:%02d\t", car.index, car.arrivingTime.getHour(), car.arrivingTime.getMinute(), car.arrivingTime.getSecond()));
        output.append("\nCars on Bridge: ").append(carsOnBridge).append("\n");
        return output.toString();
    }


    @Override
    public void run() {
        long lastPrint = System.currentTimeMillis();
        while (this.waitingCars.size() <= Variables.MAX_WAITING_CARS) {
            synchronized (this) {
                if (carsOnBridge < Variables.MAX_CARS_ON_BRIDGE && !this.waitingCars.isEmpty())
                    crossing(this.waitingCars.getFirst());
            }
            if (System.currentTimeMillis() - lastPrint >= Variables.PRINT_INTERVAL) {
                System.out.println(this);
                lastPrint = System.currentTimeMillis();
            }
        }
    }
}
