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

import cc.Parameters;
import cc.monitors.CompositeMonitor;
public class Client extends CompositeMonitor implements Interface {
	DatagramSocket socket;
	Receiver receiver;
	
	private static Client instance = null;

	static public Client getInstance(){
		return instance;
	}
	
	private Client() {
		instance = this;
		
		try {
			socket = new DatagramSocket();
			receiver = new Receiver(instance);
			request();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		//Attach Monitors
		attachMonitor(new LogMonitor());
	}

	public void terminate() {
		//Attach Monitors
		detachAll();
		receiver.terminate();
		sendMsg("terminate");
	}

	public static void main(String args[]) throws IOException {
		//Parse initial parameters
		Parameters.parseArgs(args);
		//Client client = Client.getInstance();
		Client client = new Client();
		
		while (System.in.read() == -1);
		
		client.terminate();
	}

	private void sendMsg(String s) {
		s += ";";
		try {
			DatagramPacket msg =
				new DatagramPacket(
					s.getBytes(),
					s.getBytes().length,
					InetAddress.getByName(Parameters.getHost()),
					Parameters.getPort());
			socket.send(msg);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sleep(int milliseconds) {
		sendMsg("sleep;" + milliseconds);
	}

	public void keepAlive() {
		sendMsg("keepalive");
	}

	public void setDelay(int delay) {
		sendMsg("delay;" + delay);
	}

	public void setSize(int size) {
		sendMsg("size;" + size);
	}

	private void request() throws UnknownHostException, IOException {
		//Request format: 
		String request = "request;" +
			receiver.getIP()
				+ ";"
				+ receiver.getPort()
				+ ";"
				+ Parameters.getSize()
				+ ";"
				+ Parameters.getDelay()
				+ ";"
				+ Parameters.getPair();
				sendMsg(request);
	}
}