{% if not included %}
{% extends 'index.html' %}
{% endif %}

{% set included = True %}

{% block title %}<title>Sequencer</title>{% endblock title %}

{% block content %}

<h3>Ob list</h3>

<div class="row mb-2">

  <label for="ob-list-options" class="col-2 col-form-label">Load OB</label>
  <div class="col">
    <select id="ob-list-options" class="form-select">
      <option  selected disabled hidden>
        -- Select a saved OB --
      </option>
      {% for ob in data %}
      <option data-index="{{loop.iterator}}" value="{{ob['@OBID']}}">
        {{ob['@OBID']}}
      </option>
        {% endfor %}
    </select>
  </div>

  <div class="col-auto">
    <button class="btn btn-primary" id="start-sequencer">Start</button>
  <!--   <button class="btn btn-secondary" id="pause-sequencer">Pause</button> -->
    <button class="btn btn-secondary" id="resume-sequencer">Continue</button>
  <!--   <button class="btn btn-secondary" id="repeat-sequencer">Try again</button> -->
    <button class="btn btn-primary" id="stop-sequencer">Stop</button>
  </div>

</div>

{% endblock content %}


{% block footer %}
  <footer class="h-100 mb-3 mx-0 overflow-hidden">
    <figure class="card h-100 border rounded bg-white">
      <figcaption class="card-header"> Sequencer log
        <button class="btn btn-primary float-end" onclick="$('#stream-output').html('')">Clear</button>
      </figcaption>
      <div class="card-body p-0 m-0 overflow-hidden">
        <pre class="ms-3 me-3 list-group h-100 list-group-flush rounded-0">
          <code class="h-100 scrollable overflow-auto"
                id="stream-output"
                style="display:flex; flex-direction:column-reverse;">

          </code>
        </pre>
      </div>
    </figure>
  </footer>


<script>

  /////////////////////////////
  /// STREAM
  /////////////////////////////

  var source = new EventSource('stream'); // in templates.py
  var ansi_up = new AnsiUp;
  source.onmessage = function(e) {
      //console.log(e.data)
      var line = e.data
      $("#stream-output").prepend(
          '<div>'+ansi_up.ansi_to_html(line)+'</div>'
          //$('<div/>').text(line).html()+'<br/>'
      );
  }

  /////////////////////////////
  /// REST
  /////////////////////////////

  $("#start-sequencer").on("click", function(e){
      console.log("clicked "+$(this))
      var data = $("#ob-list-options").val()
      console.log(data)
      $(this).crud("POST", "/api/sequencer/run", data)
  })

  $("#stop-sequencer").on("click", function(e){
      $(this).crud("DELETE", "/api/sequencer/run")
  })

  $("#pause-sequencer").on("click", function(e){
      $(this).crud("PUT", "/api/sequencer/run", false)
  })

  $("#resume-sequencer").on("click", function(e){
      $(this).crud("PUT", "/api/sequencer/run", true)
  })

  $("#repeat-sequencer").on("click", function(e){
      $(this).crud("PUT", "/api/sequencer/run", null)
  })


</script>

{% endblock footer%}
