/*
 * Created on 20-apr-2004
 */
package convFramework.traffic;

import java.net.*;
import convFramework.domain.*;
import convFramework.exceptions.*;
import java.io.*;

/**
 * @author Lompa
 */
public class OutGate {
	
	/* campi */
	private DatagramSocket outSocket = null;
	private IMarshaller marshaller = null;
	
	/**
	 * Classe che rappresenta una porta di accesso in uscita  
	 * @param currentNode
	 * @param outSocket
	 * @param marshaller
	 */
	public OutGate(Node currentNode, DatagramSocket outSocket, IMarshaller marshaller){
		this.outSocket = outSocket;
		this.marshaller = marshaller;
	}
	
	public void send(Packet packet) throws MarshallingException, TransmissionErrorException{
		
		/* controlli */
		if (packet.getAcknowledgedPacket() != null && !packet.isAck())
			throw new TransmissionErrorException("Only answer packets can have referred packet id");
		if (packet.getPreviousPacket() != null && !packet.isSequence())
			throw new TransmissionErrorException("Only sequence packets can have previous packet id");		
		
		/* marshalling del contenuto del pacchetto */
		byte[] content = marshaller.marshall(packet);
		
		/* creazione datagram packet */
		DatagramPacket message = new DatagramPacket(content, content.length);
		
		/* impostazione destinazione */
		message.setAddress(packet.getReceiver().getAddress());
		message.setPort(packet.getReceiver().getPort());
		
		/* invio messaggio */
		try {
			outSocket.send(message);
		}
		catch(IOException e){
			throw new TransmissionErrorException(e.getMessage());
		}
	}
}
