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 List<Car> waitingCars = new ArrayList<>();
    private Set<Integer> waitingTimes = new HashSet<>();
    private int carsOnBridge = 0;

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

    public synchronized void arriving(Car car) {
        System.out.println("add");
        this.waitingCars.add(car);
        System.out.println(this.waitingCars.size());
    }

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

    @Override
    public String toString() {
        StringBuilder output = new StringBuilder("""
                Statistics:
                waiting:\s
                """);
        for (int i = 0; i < waitingCars.size(); i++) {
            output.append("Car").append(i).append(": \t");
            output.append(waitingCars.get(i).arrivingTime.getHour());
            output.append(":").append(waitingCars.get(i).arrivingTime.getMinute());
            output.append(":").append(waitingCars.get(i).arrivingTime.getSecond()).append("\n");
        }
        output
//                .append("waitingTimes: ").append(waitingTimes)
                .append("carsOnBridge: ").append(carsOnBridge);
        return output.toString();
    }

    @Override
    public void run() {
        while (Generator.RESUME) {
//                if (waitingCars.isEmpty()) continue;
            if (this.carsOnBridge < 10) {
//                    System.out.println("<10");
//                    System.out.println(waitingCars.size());
                if (!this.waitingCars.isEmpty()) {
                    System.out.println("crossing");
                    crossing(this.waitingCars.getFirst());
                }
            }
        }
    }
}
