package hu.ppke.itk.java.hakta.hf06;

import java.util.ArrayList;

public class Switch {
	private ArrayList<Thread> students = new ArrayList<>();
	private final Server myServer;
	private int NumOfConnections = 0;
	private static Object monitor = new Object();
	
	Switch(Server myServer) {
		this.myServer = myServer;
	}
	
	public void addStudents(int studentNum) {
		for (int i = 0; i < studentNum; i++)
			students.add(new Thread(new Student(this)));
	}
	
	public void start() {
		students.stream().forEach(e -> e.start());
	}
	
	public void waitToFinish() {
			for(Thread e : students)
				try { e.join(); } catch (InterruptedException e1) { e1.printStackTrace(); }
	}
	
	public Server getServer() {
		return myServer;
	}
	
	public Connection newConnection() throws TimeoverException {
		synchronized (monitor) {
			if (25 <= NumOfConnections)
				return null;
			NumOfConnections++;
			Connection newConnection = new Connection(this,myServer.newConnection()*(NumOfConnections <= 15 ? 1 : 2));
			return newConnection;
		}
	}
	
	public void disconnect() {
		synchronized(monitor) {
			NumOfConnections--;
			myServer.disconnect();
		}
	}

	public byte getTimeInterval() {
		return myServer.getTimeInterval();
	}
}
