package network;

import model.*;

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;
	
	public UDPInput(InetAddress localAddress, int port) throws SocketException {
		this.socket = new DatagramSocket(port, localAddress);
		this.socket.setBroadcast(true);
		this.messageReceived = new ArrayList<MessagePseudo>();
	}
	
	
	public MessagePseudo getMessage() {
		return this.messageReceived.remove(0);
	}
	
	
	@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();
			}
			/* Charset charset = StandardCharsets.US_ASCII;
			 String pseudo = charset.decode(ByteBuffer.wrap(inPacket.getData())).toString();
			 MessagePseudo msg = new MessagePseudo(null, null, 0, 0, 0, "");
			 msg.setPseudo(pseudo);*/
			ByteArrayInputStream byteInStream = new ByteArrayInputStream(inPacket.getData());
                ObjectInputStream objectInStream;
				try {
					objectInStream = new ObjectInputStream(byteInStream);
					MessagePseudo msg = (MessagePseudo) objectInStream.readObject();
					messageReceived.add(msg);
					 System.out.println("Message reçu, pseudo = "+msg.getPseudo()+" et num port = "+msg.getPortSrc()+"\n");
				} catch (IOException e) {
					System.out.println("Objet pas créé");
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					System.out.println("Objet pas lu");
					e.printStackTrace();
				}	
		}
	}
}
