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

package protocol;

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

public class UDPService implements ProtocolEntity {

  private static final String SEND = "Send DatReq";
  private static final String SOURCE_PORT = "Source port";
  private static final String DEST_PORT = "Destination port";

  private ProtocolEntity provider;			// protocol for service
  private Vector providerEvents;
  private PDU pduSent;
  private String name;
  private int block;					// SDU ID number
  private int sourcePort = 0;
  private int destPort = 0;

  public UDPService(String name) {
    this.name = name;
    initialise();
  }

  public void initialise() {
    block = 0;
    providerEvents = new Vector();
  }

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

  public void setProvider(ProtocolEntity provider) {
    this.provider = provider;
  }

  public void setSourcePort(int sp) {
    sourcePort = sp;
  }

  public void setDestPort(int dp) {
    destPort = dp;
  }

  public Vector<ProtocolEvent> receivePDU(PDU pdu) {
    return(new Vector<ProtocolEvent>());
  }

  public void transmitPDU(PDU pdu, ProtocolEntity dest) {
    pdu.setSource(this);
    pdu.setDestination(dest);
    providerEvents = dest.receivePDU(pdu);
    pduSent = pdu;
  }

  public Vector<String> getServices() {
    Vector<String> list = new Vector<String>();
    String s = SEND + "(D" + block + "): "
	       + SOURCE_PORT + " " + sourcePort + ", "
	       + DEST_PORT + " " + destPort;
    list.addElement(s);
    return(list);
  }

  public Vector<ProtocolEvent> performService(String s) {
    Vector<ProtocolEvent> events = new Vector<ProtocolEvent>();
    if (s.startsWith(SEND)) {
      String sdu = "D" + block;
      int spStart = s.indexOf(SOURCE_PORT) + SOURCE_PORT.length() + 1;
      int spEnd = s.indexOf(", ");
      int dpStart = s.indexOf(DEST_PORT) + DEST_PORT.length() + 1;
      int sp = Integer.parseInt(s.substring(spStart, spEnd));
      int dp = Integer.parseInt(s.substring(dpStart));
      PDU pdu = new UDPMessage("DatReq", sp, dp, sdu);
      transmitPDU(pdu, provider);
      block++;
      events.addElement(new ProtocolEvent(ProtocolEvent.SEND, pdu));
    }
    for (Enumeration e = providerEvents.elements(); e.hasMoreElements(); )
      events.addElement((ProtocolEvent) e.nextElement());
    return(events);
  }

}
