package test.sim.scenario;

import brn.sim.AbstractDriver;
import brn.sim.AbstractParams;
import brn.sim.handler.TimeBarRadioChannelHandler;
import brn.sim.handler.LinkQualityHandler;
import brn.sim.builder.*;
import brn.sim.scenario.mchannel.McExORParams;
import brn.swans.app.UdpApplication;
import test.sim.handler.McExORTestEventHandler;
import jist.swans.Node;
import jist.swans.trans.AbstractTrans;
import org.apache.log4j.Logger;

/**
 *
 */
public abstract class AbstractTestMcExOR extends AbstractDriver {

  /** logger for mac events. */
  public static final Logger log = Logger.getLogger(AbstractTestMcExOR.class.getName());

  protected void installHandlers(AbstractParams options) throws Exception {
    super.installHandlers(options);

    McExORParams opts = (McExORParams)options;
    if (opts.handlerRadioTimeBar) {
      int chNumber = ((FieldBuilder.FieldParams)opts.field).channelNumber;
      if (chNumber > 1) {
        TimeBarRadioChannelHandler chhandler = new TimeBarRadioChannelHandler();
        chhandler.registerHandlers();
        dataManager.add(chhandler);
      }
    }

    Object linkQualityObj = dataManager.getContributor(LinkQualityHandler.ID);

    if (linkQualityObj != null) {
      double sampleLen = ((MetricBuilder.EtxParams)((RouteBuilder.MCExORParams)opts.node.route).metric).tau;
      ((LinkQualityHandler)(linkQualityObj)).setSampleLen(/*to sec*/ sampleLen / 1000);
    }

    McExORTestEventHandler jeh = new McExORTestEventHandler();
    jeh.registerHandlers();

  }

  /**
   * Called after successful hookup. Overwrite if you want to do some
   * custom initialization.
   *
   * @param opts
   * @throws brn.sim.builder.BuilderException
   */
  protected void postHookUp(AbstractParams opts) throws BuilderException {
  }


  protected void setupApplication(AbstractParams opts, int nodeId, Node node) throws BuilderException {
    super.setupApplication(opts, nodeId, node);

    McExORParams params = (McExORParams)opts;

    { // transport
      Builder builder = builderProvider.getBuilder(params.udpParams);
      AbstractTrans trans = (AbstractTrans) builder.build(params.udpParams, node);
      builderProvider.addHookUp(builder, params.udpParams, node, trans);
      node.addTransport(trans);
    }

    { // app
      Builder builder = builderProvider.getBuilder(params.appParams);
      UdpApplication app = (UdpApplication) builder.build(params.appParams, node);
      if (null != app) {
        builderProvider.addHookUp(builder, params.appParams, node, app);
        node.addApplication(app);
      }
    }
  }
}
