package streamer;
import java.net.*;

import cc.Parameters;
public class Sender extends Thread implements Interface {
	private String targetHost;
	private int targetPort;
	protected int size;
	protected int delay;

	private long lastKeepAlive;
	boolean isAlive = true;
	protected int timeToWait = 0;
	
	public Sender(Request request) {
		size = request.getSize();
		delay = request.getDelay();
		targetHost = request.getHost();
		targetPort = request.getPort();
		
		lastKeepAlive = System.currentTimeMillis();
		
		start();
	}

	byte[] setHeader(int i) {
		byte buffer[] = new byte[size];
		//index;timestamp;size;delay;pair;
		long ts = System.currentTimeMillis();
		String 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];

		return buffer;
	}

	public void run() {
		InetAddress iTargetHost;
		int i = 0;
		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket();
			DatagramPacket packet;
			iTargetHost = InetAddress.getByName(targetHost);
			while (isAlive) {
				byte[] buffer = setHeader(i++); //Writes in Buffer
				packet =
					new DatagramPacket(
						buffer,
						buffer.length,
						iTargetHost,
						targetPort);
				socket.send(packet);

				timeToWait();

				checkKeepAlive();
			}
			socket.close();
			//System.out.println("Goodbye");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void checkKeepAlive() {
		if ((lastKeepAlive + (Parameters.getTimeout()*1000)) < System.currentTimeMillis())
			isAlive = false;
	}

	protected void timeToWait() throws InterruptedException {
		if (timeToWait != 0){
			Thread.sleep(timeToWait);
			timeToWait = 0;
		}
		Thread.sleep(delay);
	}

	public void sleep(int milliseconds) {
		timeToWait += milliseconds;
	}
	public void keepAlive() {
		lastKeepAlive = System.currentTimeMillis();
	}
	public void setDelay(int delay) {
		this.delay = delay;
	}
	public void setSize(int size) {
		this.size = size;
	}

	/* (non-Javadoc)
	 * @see streamer.Interface#terminate()
	 */
	public void terminate() {
		isAlive = false;
	}
}