package hu.ppke.itk.java.hakta.hf06;

import java.sql.Timestamp;
import java.util.Date;

public class Server {
	
	private final int NUMBER_OF_SWITCHES = 4;
	private final int MAX_STUDENTS = 30;
	private int NumOfConnections = 0;
	private static Object monitor = new Object();
	private byte timeInterval = 0;
	

	private Switch[] switches = new Switch[NUMBER_OF_SWITCHES];
	{
		for(int i = 0; i < 4; i++)
			switches[i] = new Switch(this);
	}
	
	public void addStudents(int switchNum, int studentNum) throws CustomException {
		if (switchNum <= 0 || NUMBER_OF_SWITCHES < switchNum)
			throw new CustomException("Ilyen terem nem létezik: " + switchNum + "!");
		if (studentNum < 0)
			throw new CustomException("Negatív számú tanuló?");
		else if (MAX_STUDENTS < studentNum)
			throw new CustomException("Sajnos 30-nál több tanuló nem fér be ebbe a terembe: " + switchNum);
		
		switches[switchNum].addStudents(studentNum);
	}
	
	public void startTest() throws InterruptedException {
		for(int i = 0; i < NUMBER_OF_SWITCHES; i++)
			switches[i].start();
		Thread.sleep(60000);
		timeInterval = 1;
		Thread.sleep(60000);
		timeInterval = 2;
		for (int i = 0; i < NUMBER_OF_SWITCHES; i++)
			switches[i].waitToFinish();
	}
	
	public int newConnection() throws TimeoverException {
		synchronized (monitor) {
			if (timeInterval == 2)
				throw new TimeoverException();
			NumOfConnections++;
			Date date = new Date();
			System.out.println(new Timestamp(date.getTime()) + ": New connection.");
			if (NumOfConnections <= 100)
				return 1;
			else
				return 2;
		}
	}

	public void disconnect() {
		synchronized(monitor) {
			NumOfConnections--;
			Date date = new Date();
			System.out.println(new Timestamp(date.getTime()) + ": Connection disconnected.");
		}
	}
	
	public byte getTimeInterval() {
		return timeInterval;
	}
}
