package network;

import model.*;

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

public class UDPOutput {
	
	private Contact user;
	private DatagramSocket socket;
	private int port;
	
	public UDPOutput(Contact user, int port) throws SocketException {
		this.user = user;
		this.port = port;
		this.socket = new DatagramSocket(port, user.getAddress());
		this.socket.setBroadcast(true);
	}
	
	
	public void send(MessagePseudo msg, InetAddress addressDest, int portSrc) throws IOException {
		
		byte[] buffer = "".getBytes();
        ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutStream = new ObjectOutputStream(byteOutStream);
        objectOutStream.writeObject(msg);
        objectOutStream.close();
        buffer = byteOutStream.toByteArray();
        DatagramPacket packet = new DatagramPacket(buffer,buffer.length,msg.getAddressDest(), msg.getPortDest());
        this.socket.send(packet);		
	}
	
	public DatagramSocket getSocket() {
		return this.socket;
	}
	
}


