package streamer;
import java.io.IOException;
import java.net.*;
import java.util.Hashtable;
import cc.Parameters;
public class Server {
	DatagramSocket socket = null;
	DatagramPacket packet = null;
	byte[] buf = null;
	Hashtable senders = null;
	public Server() throws SocketException {
		socket = new DatagramSocket();
		buf = new byte[Parameters.getMinSize()];
		packet = new DatagramPacket(buf, Parameters.getMinSize());
		senders = new Hashtable();
	}
	public static void main(String args[]) {
		//Parse initial parameters
		Parameters.parseArgs(args);
		Server server;
		try {
			server = new Server();
			server.run();
			System.in.read();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private void run() throws IOException {
		System.out.println(
			"Ready " + Server.getIP() + ":" + socket.getLocalPort());
		//Accept Loop
		while (true) {
			socket.receive(packet);
			processRequest(packet);
		}
	}
	private void processRequest(DatagramPacket packet) {
		String stringHashCode =
			packet.getAddress().toString() + ":" + packet.getPort();
		//Pega a primeira string
		java.util.StringTokenizer st =
			new java.util.StringTokenizer(new String(packet.getData()), ";");
		String token = st.nextToken();
		System.out.println("-> " + stringHashCode + ":" + token);
		if (token.equals("request")) {
			Request request = new Request(packet.getData());
			//System.out.println(
			//	"#request:" + request.getHost() + ":" + request.getPort());
			if (request.isPaired()) {
				//System.out.println("Paired");
				senders.put(stringHashCode, new PairSender(request));
			} else {
				//System.out.println("NOT Paired");
				senders.put(stringHashCode, new Sender(request));
			}
		} else if (token.equals("sleep")) {
			((Sender) senders.get(stringHashCode)).sleep(
				(new Integer(st.nextToken())).intValue());
		} else if (token.equals("keepalive")) {
			((Sender) senders.get(stringHashCode)).keepAlive();
		} else if (token.equals("size")) {
			((Sender) senders.get(stringHashCode)).setSize(
				(new Integer(st.nextToken())).intValue());
		} else if (token.equals("delay")) {
			((Sender) senders.get(stringHashCode)).setDelay(
				(new Integer(st.nextToken())).intValue());
		} else if (token.equals("terminate")) {
			((Sender) senders.get(stringHashCode)).terminate();
			senders.remove(stringHashCode);
		}
	}
	private static String getIP() {
		java.util.Enumeration interfaces;
		try {
			interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements()) {
				java.util.Enumeration IPs =
					((NetworkInterface) (interfaces.nextElement()))
						.getInetAddresses();
				while (IPs.hasMoreElements()) {
					InetAddress IP = ((InetAddress) (IPs.nextElement()));
					if (!IP.isLinkLocalAddress() && !IP.isLoopbackAddress())
						return IP.getHostAddress();
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return null;
	}
}