package hu.ppke.itk.java.hakta.hf06;

import java.util.Random;

public class Student implements Runnable {
	private Connection connection;
	private final Switch mySwitch;
	
	public Student(Switch mySwitch) {
		this.mySwitch = mySwitch;
	}

	@Override
	public void run() {
		Random rand = new Random();
		boolean downloaded = false;
		boolean workingOnServer = (rand.nextInt(10) == 0 ? true : false);
		boolean finishesEarlier = (rand.nextInt(10) == 0 ? true : false);
		if (rand.nextInt(9) < 6) { // A tanulók kétharmada még a feladat elolvasása előtt elkezdi letölteni a környezetet
			try {
				while ((connection = mySwitch.newConnection()) == null) Thread.sleep(3000);
				downloaded = connection.download();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (TimeoverException e) {
				System.err.println("Lejárt az idő??! Még le sem töltöttem a környezetet!");
			}
			connection.disconnect();
		}
		try {
			Thread.sleep(10000); // Feladat elolvasása
			if (!downloaded) { // Ha eddig nem tették volna meg (vagy esetleg nem sikerült)
				try {
					while ((connection = mySwitch.newConnection()) == null) Thread.sleep(3000);
				} catch (TimeoverException e) {
					System.err.println("Lejárt az idő??! Még le sem töltöttem a környezetet!");
				}
				downloaded = connection.download();
				connection.disconnect();
			}
			if (finishesEarlier)
				try {
					while (mySwitch.getTimeInterval() == 0) {
						if(workingOnServer)
							Thread.sleep(5000); // Dolgozik...
						else 
							Thread.sleep(20000); // Dolgozik...

						while ((connection = mySwitch.newConnection()) == null) Thread.sleep(3000);
						connection.save();
						connection.disconnect();
					}
				}
				catch(TimeoverException e) {}
			else 
				try {
					while (mySwitch.getTimeInterval() < 2) {
						if(workingOnServer)
							Thread.sleep(5000); // Dolgozik...
						else 
							Thread.sleep(20000); // Dolgozik...
	
						while ((connection = mySwitch.newConnection()) == null) Thread.sleep(3000);
						connection.save();
						connection.disconnect();
					}
				}
				catch(TimeoverException e) {}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	
}
