package cz.vutbr.feec.muller;

import java.util.Random;

import cz.vutbr.feec.simlib.Proc;

public class FT extends Proc {
	// feedback
	private FT feedback = null;
	// received 
	private int blackCounter = 0;
	private int whiteCounter = 0;
	protected final int time;
	
	public FT(int time) {
		this.time = time;
	}
	
	public FT getFeedback() {
		return feedback;
	}

	public void setFeedback(FT feedback) {
		this.feedback = feedback;
	}

	@Override
	public void action() {
		Random rnd = new Random();
		while(!getSimulation().isFinished()) {
			//sleepProc((double)((time) * (rnd.nextDouble() + 0.5)));
			// FTH ... pocet sousedu se kterym sdili pasmo
			double stime = (double)((time/5.)* (rnd.nextDouble()));
			sleepProc(stime);
			
			sendRSI();
			sleepProc((time/5.)-stime);
		}
		sleepProc(time*4./5.);
	}

	private void sendRSI() {
		if(getFeedback() != null) {
			getFeedback().receiveBlack(blackCounter);
			getFeedback().receiveWhite(whiteCounter);
		}
		resetCounters();
	}

	protected void resetCounters() {
		blackCounter = 0;
		whiteCounter = 0;
	}

	protected void receiveWhite(int value) {
		whiteCounter += value;
	}

	protected void receiveBlack(int value) {
		blackCounter += value;
	}

	public int getBlackCounter() {
		return blackCounter;
	}

	public int getWhiteCounter() {
		return whiteCounter;
	}
}
