// UDPProtocol.java	(C) I. A. Robin, K. J. Turner	04/03/06

package protocol;

import java.util.*;
import support.*;

public class UDPProtocol implements ProtocolEntity {

  private ProtocolEntity peer;
  private UDPService user;
  private Vector userEvents;
  private Medium medium;
  private String name;

  public UDPProtocol(Medium m, String name) {
    this.name = name;
    medium = m;
    initialise();
  }

  public void initialise() {
    userEvents = new Vector();
  }

  public String getName() {
    return(name);
  }

  public void setPeer(ProtocolEntity peer) {
    this.peer = peer;
  }

  public void setUser(ProtocolEntity user) {
    this.user = (UDPService)user;
  }

  public Vector<ProtocolEvent> receivePDU(PDU pdu) {
    Vector<ProtocolEvent> events = new Vector<ProtocolEvent>();
    UDPMessage ud;
    String pduType = "";
    if (pdu != null) {
      pduType = pdu.type;
      int sp = ((UDPMessage)pdu).sourcePort;
      int dp = ((UDPMessage)pdu).destPort;
      if (pduType.equals("DatReq")) {			// DatReq from user
	ud = new UDPMessage("DT", sp, dp, pdu.getSDU());
	transmitPDU(ud, peer);
	events.addElement(new ProtocolEvent(ProtocolEvent.TRANSMIT, ud));
      }
      if (pduType.equals("DT")) {			// data PDU received
	ud = new UDPMessage("DatInd", sp, dp, pdu.getSDU());
	transmitPDU(ud, user);
	events.addElement(new ProtocolEvent(ProtocolEvent.DELIVER, ud));
	}
      }
    return(events);
  }

  public void transmitPDU(PDU pdu, ProtocolEntity dest) {
    pdu.setSource(this);
    pdu.setDestination(dest);
    if (dest == peer)
      userEvents = medium.receivePDU(pdu);
    else
      userEvents = user.receivePDU(pdu);
  }

  public Vector<String> getServices() {
    Vector<String> list = new Vector<String>();
    return(list);
  }

  public Vector<ProtocolEvent> performService(String s) {
    Vector<ProtocolEvent> events = new Vector<ProtocolEvent>();
    for (Enumeration e = userEvents.elements(); e.hasMoreElements(); )
      events.addElement((ProtocolEvent) e.nextElement());
    return(events);
  }

}
