package pair;
import java.io.IOException;
import java.net.*;

import cc.Parameters;

public class Sender extends Thread {
	private boolean finish = false;

	public void terminate() {
		finish = true;
		//this.interrupt();
	}
	public static void main(String args[]) {
		//Parse initial parameters
		Parameters.parseArgs(args);

		Sender sender;
		try {
			sender =
				new Sender(
					Parameters.getHost(),
					Parameters.getPort(),
					Parameters.getPairType(),
					Parameters.getSize(),
					Parameters.getIntraPair(),
					Parameters.getInterPair());

			while (System.in.read() == -1);
			System.out.println("I am going...");
			sender.terminate();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	int type, size, intra, inter;

	String host = null;
	int port = 0;

	Sender(String host, int port, int type, int size, int intra, int inter)
		throws SocketException, UnknownHostException {
		
		this.host = host;
		this.port = port;
		this.type = type;
		this.size = size;
		this.intra = intra;
		this.inter = inter;
		
		start();
	}

	public void run() {

		InetAddress iHost;
		int interPairDelay = Parameters.getInterPair();

		try {
			iHost = InetAddress.getByName(host);

			DatagramSocket socket = new DatagramSocket();

			byte smallHeaderBuffer[] = new byte[32]; smallHeaderBuffer[0] = 'h';
			byte bigHeaderBuffer[] = new byte[size]; bigHeaderBuffer[0] = 'h';
			byte pairBuffer[] = new byte[size]; pairBuffer[0] = 'p';

			DatagramPacket smallHeaderPacket = new DatagramPacket(smallHeaderBuffer, smallHeaderBuffer.length, iHost, port);
			DatagramPacket bigHeaderPacket = new DatagramPacket(bigHeaderBuffer, bigHeaderBuffer.length, iHost, port);
			DatagramPacket pairPacket = new DatagramPacket(pairBuffer, pairBuffer.length, iHost, port);
		
			while (!finish) {
				if (type == 1) { //cp
					socket.send(smallHeaderPacket);
				} else { //pp
					socket.send(bigHeaderPacket);
				}
				
				if (intra != 0)
					Thread.sleep(intra);

				socket.send(pairPacket);

				if (inter != 0)
					Thread.sleep(inter);
			}
			socket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
