package network;

import model.*;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.*;
import java.util.ArrayList;


public class UDPInput extends Thread{
	
	private DatagramSocket socket;
	private ArrayList<MessagePseudo> messageReceived;
	private PropertyChangeSupport support;
	
	public UDPInput(InetAddress localAddress, int port) throws SocketException {
		this.socket = new DatagramSocket(port, localAddress);
		this.socket.setBroadcast(true);
		this.messageReceived = new ArrayList<MessagePseudo>();
		this.support = new PropertyChangeSupport(this);
	}
	
	public ArrayList<MessagePseudo> getListMessage (){
		return this.messageReceived;
	}
	
	public MessagePseudo getMessage() {
		return this.messageReceived.remove(0);
	}
	
	
	public void addPropertyChangeListener(PropertyChangeListener pcl) {
		this.support.addPropertyChangeListener("Msg UDP Recu", pcl);
	}
	
	
	@Override
	public void run() {
		byte[] buffer = new byte[5000];
		while(true) {
			DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);
			try {
				socket.receive(inPacket);
			} catch (IOException e) {
				System.out.println("Packet UDP non reçu\n");
				e.printStackTrace();
			}
			ByteArrayInputStream byteInStream = new ByteArrayInputStream(inPacket.getData());
                ObjectInputStream objectInStream;
				try {
					objectInStream = new ObjectInputStream(byteInStream);
					MessagePseudo msg = (MessagePseudo) objectInStream.readObject();
					messageReceived.add(msg);
					this.support.firePropertyChange("Msg UDP Recu", this.messageReceived.size() -1, this.messageReceived.size());
				
				} catch (IOException e) {
					System.out.println("Objet pas créé");
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					System.out.println("Objet pas lu");
					e.printStackTrace();
				}	
		}
	}
}
