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

package protocol;

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

public class SWP5Service implements ProtocolEntity {

  public static final String DAT_REQ  = "Data Request";

  private ProtocolEntity provider;			// protocol for service
  private Vector providerEvents;
  private PDU pduSent;
  private String name;
  private boolean sending;				// sending/receiving
  private int block;               			 // data seq. no.
  private boolean okToSend;				// OK to send DatReq

  public SWP5Service(String name, boolean sending) {
    this.name = name;
    this.sending = sending;
    initialise();
  }

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

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

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

  // DatReq allowed only when okToSend is true
  // (sender protocol window not closed)

  public void setOKToSend(boolean ok) {
    okToSend = ok;
  }

  // accept message but don't need to do anything with it

  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>();
    if (sending && okToSend)
      list.addElement("Send " + DAT_REQ + "(D" + block + ")");
    return(list);
  }

  public Vector<ProtocolEvent> performService(String s) {
    Vector<ProtocolEvent> events = new Vector<ProtocolEvent>();
    if (sending && s.startsWith("Send " + DAT_REQ)) {
      String sdu = "D" + block;
      transmitPDU(new PDU("DatReq", sdu), provider);
      block++;
      events.addElement(new ProtocolEvent(ProtocolEvent.TRANSMIT, pduSent));
    }
    for (Enumeration e = providerEvents.elements(); e.hasMoreElements(); )
      events.addElement((ProtocolEvent) e.nextElement());
    return(events);
  }

}
