// UDPMedium.java	(C) I. A. Robin, K. J. Turner	01/03/01

package protocol;

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

public class UDPMedium extends Medium {

  public UDPMedium() {
    super();
  }

  // identify and return PDU currently on channel with
  // type and parameters matching those described in given string
  // parameters are: (source port, destination port, SDU)

  protected PDU getMatchingPDU(String s) {
    UDPMessage ud;
    int sp = -1;
    int dp = -1;
    String sdu = "";
    // extract name of source entity for this datagram:
    int sourceStart = s.indexOf('[') + 1;
    int sourceEnd = s.indexOf( ']' );
    String sourceName = s.substring(sourceStart, sourceEnd);
    // get type and parameters of PDU from action string
    // PDU type starts after first space following "Deliver" or "Lose":
    int typeStart = s.indexOf(' ') + 1;
    int typeEnd = s.indexOf( '(' );
    String type = s.substring(typeStart, typeEnd);
    String[] params = getParams(s);
    sp = Integer.parseInt(params[0]); // source port
    dp = Integer.parseInt(params[1]); // destination port
    sdu = params[2];
    // try to match PDU type and seq with a PDU currently on channel:
    for (Enumeration e = pdus.elements(); e.hasMoreElements(); ) {
      ud = (UDPMessage)e.nextElement();
      if (ud != null && ud.type.equals(type)
           && ud.getSource().getName().equals(sourceName)
           && sp == ud.sourcePort && dp == ud.destPort
           && sdu.equals(ud.getSDU())) {
           return ud;
      }
    }
    return null;					// no match found
  }

}
