package brn.sim.handler;

import java.util.Hashtable;

import jist.swans.mac.AbstractMac;
import jist.swans.misc.Event;

import org.apache.log4j.Logger;

import brn.sim.DataManager;
import brn.sim.DataManager.DataContributor;
import brn.sim.data.TimeBar;

public class TimeBarTXOPStateHandler extends DataContributor {

  public static final Logger log = Logger.getLogger(TimeBarTXOPStateHandler.class);

  // ////////////////////////////////////////////////
  // constants
  //

  private static final String ID = "TimeBarTXOPStateHandler";


  // ////////////////////////////////////////////////
  // locals
  //
  private Hashtable lastEventTime = new Hashtable();
  private TimeBar timeBar;

  // ////////////////////////////////////////////////
  // initialization
  //
  public TimeBarTXOPStateHandler() {
    timeBar = new TimeBar(new String[] {"Global", "Mac", "TXOP Timebar"});
  }

  public void registerHandlers() {
    Event.addHandler(AbstractMac.TXOPEvent.class, new Event.Handler() {
      public void handle(Event event) {
        AbstractMac.TXOPEvent ev = (AbstractMac.TXOPEvent) event;      
        
        Object lastTime = lastEventTime.get(new Integer(ev.nodeId));
        if (lastTime == null) {
          lastEventTime.put(new Integer(ev.nodeId), new Long(0));
          lastTime = lastEventTime.get(new Integer(ev.nodeId));
        }

        long lastTimeL = ((Long)lastTime).longValue();
        
        if (ev.hasTXOP == false && lastTimeL > 0) {
  
          int node = ev.nodeId;
          
          if (ev.internalNode != -1) {
            node *= 10;
            node += ev.internalNode;
          }
          
          timeBar.add(node, lastTimeL, ev.time,
              TimeBar.COLOR_DARK_RED, "TXOP" // + ev.remainingTXOP 
                                                 );
  //                , ev.detail + " dur:" + duration);
        }
        lastEventTime.put(new Integer(ev.nodeId), new Long(ev.time));
      }
    });
  }


  // ////////////////////////////////////////////////
  // implementation
  //

  /**
   * @return the radioTimeBar
   */
  public TimeBar getTimeBar() {
    return timeBar;
  }

  /*
   * (non-Javadoc)
   * @see brn.sim.DataManager.DataContributor#getId()
   */
  public String getId() {
    return ID;
  }

  /* (non-Javadoc)
   * @see brn.sim.DataManager.DataContributor#setDataManager(brn.sim.DataManager)
   */
  public void setDataManager(DataManager manager) {
    super.setDataManager(manager);
    manager.addData(this, timeBar);
  }
}
