package streamer;
import cc.Parameters;
public class PairSender extends Sender {
	long lastPairPacketTimestamp;
	boolean nextPairIsPacket = false;
	boolean currentPairIsPacket = false;
	
	public PairSender(Request request) {
		super(request);
		lastPairPacketTimestamp = System.currentTimeMillis();
	}
	
	byte[] setHeader(int i) {
		String ret;
		byte buffer[] = new byte[size];
		long ts = System.currentTimeMillis();

		if (currentPairIsPacket) {
			ret = i + ";" + ts + ";" + size + ";" + delay + ";p;";
			lastPairPacketTimestamp = ts;
		} else {
			ret = i + ";" + ts + ";" + size + ";" + delay + ";c;";
		}
		
		//System.out.println(ret);

		for (int j = 0; j < ret.length() && j < size; j++)
			buffer[j] = ret.getBytes()[j];

		if (!nextPairIsPacket && (lastPairPacketTimestamp + Parameters.getInterPair()) < ts) {
			nextPairIsPacket = true;
		}

		return buffer;
	}

	protected void timeToWait() throws InterruptedException {
		if (nextPairIsPacket) {
			nextPairIsPacket = false;
			currentPairIsPacket = true;
		} else if (currentPairIsPacket) {
			if (timeToWait != 0){
				Thread.sleep(timeToWait);
				timeToWait = 0;
			}
			Thread.sleep(2*delay + 10); //sabemos que a chamada custa 10 ms
			currentPairIsPacket = false;
		} else {
			super.timeToWait();
		}
	}
}