package streamer;

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

import cc.Parameters;
import cc.events.Event;

public class Receiver extends Thread {
	private boolean alive = true;
	DatagramSocket socket = null;
	DatagramPacket packet = null;
	Client parent = null;

	byte[] buf = null;

	Receiver(Client parent) throws SocketException, UnknownHostException {
		this.parent = parent;
		socket = new DatagramSocket();
		buf = new byte[Parameters.getMaxSize()];
		packet = new DatagramPacket(buf, Parameters.getMaxSize());

		//System.out.println("->" + getIP() + ":" + getPort());
		start();
	}

	public void run() {
		try {
			while (alive) {
				socket.receive(packet);
				parent.update(new Event(packet));
			}
			System.out.println("saida receiver2");
		} catch (SocketException e) {
			//e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public int getPort() {
		return socket.getLocalPort();
	}

	public 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;
	}

	public void terminate() {
		alive = false;
		socket.close();		
	}
}
