package cz.vutbr.feec.burget.advanced;

import java.util.HashSet;
import java.util.Random;

public class FT extends Member {
	
	private double time;

	public FT(double rftPeriod) {
		this.time = rftPeriod;
	}

	@Override
	public void afterFeedbackSent() {
		// nedelej nic
	}

	@Override
	public void beforeFeedbackSent() {
		// cekej 5 sec * nahodny interval:<0.5, 1.5>
		
		Random rnd = new Random();
		double randTime = time * ( 0.5 + rnd.nextDouble());
		sleepProc(randTime);
	}

	double lasttime = 0;
	
	@Override
	public void onFeedbackSent(Member m) {
		if(m != null) {
			m.onFeedbackReceived(this);
		}
		// reset
		receivedSet.clear();
		receivedMessages = 0;
		duplicity = 0;
	}
	
	private int receivedMessages = 0;
	private int duplicity = 0;
	private HashSet<Integer> receivedSet = new HashSet<Integer>();
	
	@Override
	public synchronized void onFeedbackReceived(Member m) {
		// pocet clenu
		if(m instanceof Receiver) {
			receivedMessages++;
//			System.out.println("RECV FROM - ");
		} else {
			FT f = (FT)m;
			receivedMessages += f.getReceivedMessages();
//			System.out.println("FT   FROM - "+f.getReceivedMessages());
		}
		// duplicity
		if(receivedSet.contains(m.getMemberId())) {
			duplicity++;
		}
		receivedSet.add(m.getMemberId());
		
//		System.out.println("Obdrzena odezva od: "+m);
	}
	
	@Override
	public String toString() {
		return "FT:"+getMemberId();
	}

	public int getReceivedMessages() {
		return receivedMessages;
	}
}
