package fr.uga.miashs.cours.attenteactive;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Scanner;

class Cours {
	private Object debutCours;
	private boolean commence;
	
	public Cours() {
		debutCours = new Object();
		commence=false;
	}
	
	public void suivre(String name) {
		synchronized (debutCours) {
			if (!commence) {
				System.out.println(name+" attend le début du cours");
				try {
					debutCours.wait();
					System.out.println(name+" dit : Chut le cours commence!");
				} catch (InterruptedException e) {
					System.out.println("Le prof n'est pas arrivé");
				}
			} else {
				System.err.println(name+" est à la bourre...");
			}
		}
	}
	
	public void donner() {
		synchronized (debutCours) {
			commence=true;
			debutCours.notifyAll();
		}
	}
	
}

public class AttenteActive {

	// Il faut créer un fichier etudiant.txt dans la racine du projet avec le nom d'un etudiant par ligne
	public static void main(String[] args) throws IOException {
		
		Cours leCoursDeSystemes = new Cours();
		
		// creation des Threads "étudiants"
		Scanner sc = new Scanner(Paths.get("etudiants.txt"));
		while (sc.hasNextLine()) {
			String etudiant = sc.nextLine();
			new Thread() {
				public void run() {
					try {
						Thread.sleep((long) (Math.random()*5000));
						System.out.println(etudiant+" arrive...");
						leCoursDeSystemes.suivre(etudiant);
						
					} catch (InterruptedException e) {}
					
					
				}
			}.start();
		}
		
		// Thread du "prof"
		new Thread() {
			public void run() {
				try {
					Thread.sleep(4000);
					System.err.println("Le prof arrive !");
					leCoursDeSystemes.donner();
					
				} catch (InterruptedException e) {}
			}
		}.start();
		

	}

}
