package cc;
import java.net.*;
import java.util.*;

import cc.monitors.*;

public class Receiver extends Streamer{

    DatagramSocket socket = null;
    DatagramPacket packet = null;
	byte[] buf = null;
    
	Vector listOfMonitors = new Vector();    
    
    Receiver () throws SocketException, UnknownHostException{
        socket = new DatagramSocket();
        buf = new byte[Parameters.getMaxSize()];
    }

    public void run(){
        try{
			while(!finish){
                packet = new DatagramPacket(buf, Parameters.getMinSize());
                socket.receive(packet);
                //System.out.print(".");

				notifyMonitors(new Event(packet));
            }

			socket.close();
			completeStreaming();
      }
        catch(Exception e){
            e.printStackTrace();
        }
    }

	public int getPort() throws java.net.SocketException {
		return socket.getLocalPort();
	}

	public String getIP() throws java.net.SocketException {
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        
        while (interfaces.hasMoreElements()){
            Enumeration IPs = ((NetworkInterface) (interfaces.nextElement())).getInetAddresses();
            while (IPs.hasMoreElements()){
                InetAddress IP = ((InetAddress) (IPs.nextElement()));
                if (!IP.isLinkLocalAddress() && !IP.isLoopbackAddress())
                    return IP.getHostAddress();
            }
        }
        return null;
    }

 
	public void attach (AbstractMonitor monitor){
		listOfMonitors.add(monitor);
	}

	public void detach (AbstractMonitor monitor){
		monitor.terminate();
		listOfMonitors.remove(monitor);
	}

	public void detachAll (){
		while (!listOfMonitors.isEmpty()){
			detach((AbstractMonitor) listOfMonitors.firstElement());
		}
	}

	void notifyMonitors(Event e){
		//System.out.print("X");
		for (int i=0 ; i<listOfMonitors.size() ; i++){
			//System.out.print("Y");
			((AbstractMonitor) listOfMonitors.elementAt(i)).update(e);
		}
	}
}

