package brn.sim.scenario.coverage;

import jist.swans.Node;
import jist.swans.misc.Util;

import org.apache.log4j.Logger;

import brn.sim.AbstractDriver;
import brn.sim.AbstractParams;
import brn.sim.builder.Builder;
import brn.sim.builder.BuilderException;
import brn.sim.builder.MetricBuilder;
import brn.sim.handler.LinkQualityHandler;
import brn.swans.route.metric.RouteEtxEttMetric;

/**
 * Get the Link Qualities for nodes with different distances.
 *
 * @author kurth
 */
public class LinkQuality extends AbstractDriver {

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

  private LinkQualityHandler linkQualityHandler;

  private boolean started = false;

  //////////////////////////////////////////////////
  // initialize
  //

  /**
   * Constructa a new test object.
   */
  public LinkQuality() {
  }


  //////////////////////////////////////////////////
  // setup
  //

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

    LinkQualityParams params = (LinkQualityParams) options;
    MetricBuilder.EtxParams opts = (MetricBuilder.EtxParams) params.metric;

    if (null != linkQualityHandler)
      linkQualityHandler.setSampleLen(/*to sec*/ opts.tau / 1000);
  }


  /*
   * (non-Javadoc)
   *
   * @see brn.sim.AbstractDriver#setupApplication(brn.sim.AbstractParams, int,
   *      jist.swans.Node)
   */
  protected void setupApplication(AbstractParams params, int nodeId, Node node)
      throws BuilderException {
    super.setupApplication(params, nodeId, node);
    LinkQualityParams opts = (LinkQualityParams) params;

    if (null != opts.metric)  {
      Builder builder = builderProvider.getBuilder(opts.metric);
      RouteEtxEttMetric metric = (RouteEtxEttMetric) builder.build(opts.metric, node);
      builderProvider.addHookUp(builder, opts.metric, node, metric);

      if (!opts.singeSender || !started) {
        metric.getProxy().start();
        started  = true;
      }
    }
  }

  //////////////////////////////////////////////////
  // implementations
  //


  /**
   * Main method for link quality measurements.
   *
   * @param args command line args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    LinkQuality test = new LinkQuality();

    if (args.length < 1) {
      test.showUsage();
      return;
    }

    try {
      LinkQualityParams options = (LinkQualityParams) (Util.readObject(args[0]));
      test.run(options);
    }
    catch (Throwable e) {
      e.printStackTrace();
      System.exit(1);
    }
  }

}
