{% extends "tabbed.html" %} {% block head %}
<script src="js/vega.min.js"></script>
<script src="js/vega-embed.min.js"></script>
<script src="util.js"></script>
<link rel="stylesheet" type="text/css" href="css/spinkit.css" /> {% endblock %}
{% block tabcontent %}

{% if vega_spec is defined %}
<div class="row">

  <div class="col-lg-8">
    <div id="plot">
      <div id="loading" class="spinner">
        <div class="rect1"></div>
        <div class="rect2"></div>
        <div class="rect3"></div>
        <div class="rect4"></div>
        <div class="rect5"></div>
      </div>
    </div>
  </div>

  <div class="col-lg-4">
    <div class="row">
      <div class="col-lg-12">
        <h3>Plot Controls</h3>
      </div>
    </div>

    <div class="row">
      <div class="col-lg-12" id="toolbar"></div>
    </div>

    <div class="row">
      <div class="col-lg-12" id="metadata-category"></div>
    </div>

    <div class="row">
      <div class="col-lg-12" id="sampling-depth-slider"></div>
    </div>

    <div class="row">
      <div class="col-lg-12" id="text-field"></div>
    </div>
  </div>

</div>

{% set loading_selector = '#loading' %}
{% include 'js-error-handler.html' %}
<script id="spec" type="application/json">
{{ vega_spec }}
</script>

<script type="text/javascript">
  $(document).ready(function() {
    var spec = JSON.parse(document.getElementById("spec").innerHTML);

    // Try and come up with a good initial estimate of plot dimensions,
    // based on the browser dimensions.
    var opts = {
      width: $("#plot").width(),
      height: $("#plot").width() / 2.5
    };

    vegaEmbed("#plot", spec, opts)
      .then(function(result) {
        result.view.logLevel(vega.Warn);
        // Stash the view object in global namespace for debugging purposes.
        // Check out https://vega.github.io/vega/docs/api/debugging/
        // for more details.
        window.v = result.view;
      })
      .catch(function(error) {
        // From 'js-error-handler.html'
        handleErrors([error], $("#plot"));
      });

    // Clean up the vega-embed toolbar
    var toolbar = $("div .vega-actions").detach();
    toolbar.addClass("btn-group");
    toolbar.children("a").each(function() {
      // NOTE: We're just skipping this bit until we get the plot working with
      // Vega 5
      if(this.innerHTML == "Open in Vega Editor"){
        this.remove()
        return true
      }
      $(this).addClass("btn btn-default");
    });

    toolbar.appendTo("#toolbar");

    var category = $("#metadata-category .vega-bind");
    category
      .children(".vega-bind-name")
      .replaceWith("<label> Metadata Category &nbsp;</label>");
    category.children("select").addClass("form-control");

    var samplingDepthSlider = $("#sampling-depth-slider .vega-bind");
    $(samplingDepthSlider)
      .find("label")
      .remove();
    $(samplingDepthSlider)
      .find("input")
      .attr("id", "range-slider");
    $(samplingDepthSlider)
      .find("input")
      .attr("oninput", "sliderHelperFunction(this.value);");
    $(samplingDepthSlider).prepend(
      "<label> Sampling Depth &nbsp; </label> <br>"
    );
    $(samplingDepthSlider).append(
      '<br> <input id="text-box" class="form-control" type="number" value="0" min="0" oninput="textBoxHelperFunction(this.value);" />'
    );
    $(samplingDepthSlider).append("(zero implies no even sampling)");
    samplingDepthSlider.children(".vega-bind-name").replaceWith("");

    var rotateLabels = $("#rotate-labels .vega-bind");
    rotateLabels
      .children(".vega-bind-name")
      .replaceWith("<label> Rotate Labels &nbsp;</label>");
    rotateLabels.children("checkbox").addClass("form-control");
  });
</script>
{% else %}
<div class="row">
  <div class="col-lg-4">
    <div class="row">
      <div class="col-lg-12" id="sampling-depth-slider">
        <label> Sampling Depth &nbsp; </label> <br>
        <input id="range-slider" type="range" min="0" max="{{max_count}}" value="0" class="slider" oninput="sliderHelperFunction(this.value);"> <br>
        <input id="text-box" class="form-control" type="number" value="0" min="0" oninput="textBoxHelperFunction(this.value);"/>
        <br>
        (zero implies no even sampling)
        <div class="row">
          <div class="col-lg-12" id="text-field"></div>
        </div>
      </div>
    </div>
  </div>
</div>

{% endif %}

<div class="row">
  <div class="col-lg-8">
    <table id="feature-table" class="table table-striped">
      <thead>
        <tr>
          <th scope="col">Sample ID</th>
          <th scope="col">Frequency</th>
        </tr>
      </thead>
      <tbody id="table-body"></tbody>
    </table>
  </div>
</div>

<script id="table-data" type="application/json">
{{ sample_frequencies_json }}
</script>

<script type="text/javascript">
  var totalFrequencies = {{total_frequencies}};
  var sampleCount = {{number_of_samples}};
  var defaultDescription = "Retained " + (totalFrequencies.toLocaleString('en'))
                                       + " (100.00%) features in "
                                       + sampleCount + " (100.00%) samples at the specifed sampling depth.";


  var textField = document.getElementById('text-field');
  var tableBody = document.getElementById("table-body");
  var table = document.getElementById("feature-table");

  // when the viz loads the default description is displayed
  textField.innerHTML = defaultDescription;

  let sampleTable = JSON.parse(document.getElementById("table-data").innerHTML);
  let sampleFrequencies = sampleTable["Frequency"];
  // get object keys and store them in an ascending order based on the key value
  // this order is used to create the table rows
  sortedSampleIDs = Object.keys(sampleFrequencies).sort(function(a, b) {
    return sortIDs(a, b, sampleFrequencies)
  });

  formatTable(tableBody, sampleTable, sortedSampleIDs);

  function updateTableandText(samplingDepth) {
    let retainedSampleCount = 0;

    // start the counter at 1 to ignore the header row
    for (var i = 1; row = table.rows[i]; i++) {
      // The value in table is formatted as a string for display to the user,
      // but the value in sampleFrequencies is formatted as an int for data
      // manipulation, so we use the ID we are on in table to get the frequency
      // from sampleFrequencies.
      const sampleID = row.cells[0].innerText;
      const sampleFrequency = sampleFrequencies[sampleID];

      if (sampleFrequency < samplingDepth) {
        row.className = "danger";
      } else {
        row.className = "";
        retainedSampleCount += 1;
      }
    }
    if (samplingDepth == 0){
      textField.innerHTML = defaultDescription;
    }
    else{
      var retainedFeatureCount = retainedSampleCount * samplingDepth;
      textField.innerHTML = "Retained " + formatter.format(retainedFeatureCount)
                                        + " (" + (retainedFeatureCount/totalFrequencies*100).toFixed(2) + "%) features in "
                                        + retainedSampleCount + " (" + (retainedSampleCount/sampleCount*100).toFixed(2)
                                        +  "%) samples at the specifed sampling depth.";
    }
  }


  function updateSliderVal(val) {
    var slider = document.getElementById("range-slider");
    slider.value = val;
    slider.dispatchEvent(new Event("change"));
    slider.dispatchEvent(new Event("input"));
  }


  function updateBoxVal(val) {
    var num = document.getElementById("text-box");
    num.value = val;
  }


  function sliderHelperFunction(val){
    updateBoxVal(val);
    updateTableandText(val);
  }


  function textBoxHelperFunction(val){
    val = parseInt(val);
    if (val !== val) {
      val = 0;
    }

    // make sure the value in the textbox cannot exceed the max count
    if (val > {{max_count}}){
      var num = document.getElementById("text-box");
      num.value = {{max_count}};
    }
    updateSliderVal(val);
  }
</script>

{% endblock %}
{% block footer %}
{% endblock %}
