package brn.sim.handler;

import brn.sim.DataManager;
import brn.sim.data.TimeBar;
import jist.swans.misc.Event;
import jist.swans.radio.AbstractRadio;

import java.util.Hashtable;

public class TimeBarRadioChannelHandler extends DataManager.DataContributor {

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

  private final String id;

  // ////////////////////////////////////////////////
  // locals
  //

  private TimeBar radioChannelTimeBar;

  private Hashtable lastEventTime = new Hashtable();

  private EventChannelHandler handler;

  private static final byte[] colorTable = new byte[] {
    TimeBar.COLOR_WHITE,
    TimeBar.COLOR_YELLOW,
    TimeBar.COLOR_GREEN,
    TimeBar.COLOR_BLUE,
    TimeBar.COLOR_DARK_BLUE,
    TimeBar.COLOR_DARK_GREEN,
    TimeBar.COLOR_CYAN,
    TimeBar.COLOR_DARK_MAGENTA,
    TimeBar.COLOR_DARK_GRAY,
    TimeBar.COLOR_DARK_CYAN,
    TimeBar.COLOR_MAGENTA,
    TimeBar.COLOR_DARK_YELLOW,
    TimeBar.COLOR_DARK_GREEN
  };

  public class EventChannelHandler implements Event.Handler {
      public void handle(Event event) {
        AbstractRadio.RadioChannelSwitchEvent ev = (AbstractRadio.RadioChannelSwitchEvent) 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();

        byte color = -1;
        if (ev.oldChannel.getChannel() == -1) {
          color = TimeBar.COLOR_RED;
        } else {
          color = colorTable[ev.oldChannel.getChannel()];
        }

        radioChannelTimeBar.add(ev.nodeId, lastTimeL, ev.time,
            color, "" + ev.oldChannel.getChannel());

        lastEventTime.put(new Integer(ev.nodeId), new Long(ev.time));
      }
    }

  // ////////////////////////////////////////////////
  // initialization
  //

  public TimeBarRadioChannelHandler() {
    id = getClass().getSimpleName();
    radioChannelTimeBar = new TimeBar(new String[] {"Global", "Radio Channel Timebar"});
    handler = new EventChannelHandler();
  }

  public void registerHandlers() {
    Event.addHandler(AbstractRadio.RadioChannelStartSwitchEvent.class, handler);
    Event.addHandler(AbstractRadio.RadioChannelFinishSwitchEvent.class, handler);
  }


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

  /**
   * @return the radioTimeBar
   */
  public TimeBar getRadioTimeBar() {
    return radioChannelTimeBar;
  }

  /*
   * (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, radioChannelTimeBar);
  }

}
