// Carnegie Mellon University
//   Information Networking Institute and
//   School of Computer Science
//
// Master Thesis: A Monitoring Tool for Overlay Network
// By: TungFai Chan and Annie Cheng
//
// File: LinkInfoTableManager.java
// Path: eventbase/link
// Description: Manage table recorded collection of link information.
//              Entry sorted chronologically.

package eventbase.link;
import java.util.*;
import eventbase.btree.*;
import eventbase.*;

public class LinkInfoTableManager implements LinkInfoType {

  final String OBJECT_NAME = "LinkInfoTableManager";
  private BTree table;
  private MemoryManager memoryManager;

  public LinkInfoTableManager(MemoryManager m) {
    table = new BTree();
    memoryManager = m;
  }
  // perform Insertion Sort order by time
  public void InsertLinkInfoToTable (LinkInfoTableEntry entry) {
    memoryManager.insertRecord(table, entry.getTime(), entry.getBytes());
  }

  // TODO: fix so ALL info_type work also, now assume only DELAY
  public DisplayLinkInfo getLinkInfo (double t, int srcID, int tgtID, int type) {
    LinkInfoTableEntry tblEntry;
    DisplayLinkInfo retVal = new DisplayLinkInfo(srcID, tgtID);
    boolean foundS2T = false;
    boolean foundT2S = false;
    int finishCount = 0;

    if (type != ALL)
      finishCount = 2;

    byte[] buffer;
    memoryManager.setIterationPointer(table, t);
    while ((buffer = memoryManager.getPrevRecord(table)) != null) {
      tblEntry = LinkInfoTableEntry.extractFromBytes(buffer);
      if (!foundS2T && tblEntry.foundLinkWanted(srcID, tgtID, type)) {
        retVal.setSrcToTargetDelay((int)tblEntry.getVal());
        finishCount--;
        foundS2T = true;
      } else if (!foundT2S && tblEntry.foundLinkWanted(tgtID, srcID, type)) {
        retVal.setTargetToSrcDelay((int)tblEntry.getVal());
        finishCount--;
        foundT2S = true;
      }
      if (finishCount <= 0)
        return retVal;
    }
    // ahcheng - it's possible that we don't have information.
    //           not necessary to send out warning message
    // System.err.print("WARNING: " + OBJECT_NAME + ":getLinkInfo() ");
    // System.err.println("Link Info is not complete");
    return retVal;
  }


  public void printTable() {
    System.out.println();
    System.out.println("================ LinkInfoTableStart ===================" );
    System.out.println("<time srcNode tgtNode type delay>");
    LinkInfoTableEntry tblEntry;
    byte[] buffer;
    memoryManager.setIterationPointer(table, 0);
    while ((buffer = memoryManager.getNextRecord(table)) != null) {
      tblEntry = LinkInfoTableEntry.extractFromBytes(buffer);
      tblEntry.print();
    }
    System.out.println("================ LinkInfoTableEnd ===================" );
    System.out.println();
  }
}