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

{% block title %}<title>RTC plots</title>{% endblock title %}

{% block content%}

<section class="row">

<h5>plot</h5>
  {% for d in data %}

  <div class="col-3">
    <figure class="card">
      <canvas id="{{d.id}}"
              width="500" height="500"
              style="border:1px solid gray;">
        plot here
      </canvas>

      <!-- <img class="card-img-top" src="{{d.image}}"> -->

      <aside class="card-body" id="{{d.id}}-info">
        <h5 class="card-title">{{d.name}}</h5>

        <form class="row" id="f-{{d.id}}">
          <div class="col-3 col-form-label">
            <span>Color</span>
            <label for="min-{{d.id}}">min</label>
            <span>,</span>
            <label for="max-{{d.id}}">max</label>
          </div>
          <div class="col">
            <div class="input-group">
              <input id="min-{{d.id}}" type="number" class="form-control">
              <input id="max-{{d.id}}" type="number" class="form-control">
            </div>
          </div>
        </form>

        <dl>
          {% for k, v in d.info %}
          <div class="row">
            <dt class="col">{{v}}</dt>
            <dd id="image-{{k}}-{{d.id}}" class="col">value</dd>
          </div>
          {% endfor %}
        </dl>

      </aside>
    </figure>
  </div>
  <script>
  </script>
  {% endfor %}

</section>

<script type="module">

  import * as d3 from "https://cdn.jsdelivr.net/npm/d3@7.7.0/+esm";
  //import * as d3 from "https://cdn.skypack.dev/d3@7";

  function update_color_scale(image, imgMin, imgMax, totFlux, id, mask){

      var min = $("#min-"+id).val()
      var max = $("#max-"+id).val()

      if (min=="")
          min = imgMin
      if (max=="")
          max = imgMax

      if (!mask){ // cred
          $("#image-min-"+id).text(imgMin)
          $("#image-max-"+id).text(imgMax)
          $("#image-tot_flux-"+id).text(totFlux)
      }

      if($("#image-wx-"+id)){ // cloud
          $("#image-wx-"+id).text(image.wx / 2 * image.image_shape[0] )
          $("#image-wy-"+id).text(image.wy / 2 * image.image_shape[1] )

          $("#image-RMS_X-"+id).text(image.RMS_X / 2 * image.image_shape[0] )
          $("#image-RMS_Y-"+id).text(image.RMS_Y / 2 * image.image_shape[1] )
//          $("#image-cloud_samples"+id).text(image.RMS_X / 2 * image.image_shape[0] )
          //console.log("AAAAA "+id)
          //console.log(image.samples)


      }

      return [min, max]

  }

  /////////////////////////////
  /// DRAWINGS
  /////////////////////////////

  function draw_circle(image, id, stroke="red", radius=5, fill="transparent", strokeWidth=2) {
      var canvas = document.getElementById(id);

      //var size = canvas.width/64 *radius // radius
      var size = canvas.width/image.data.length/3 * radius // radius
      var ctx = canvas.getContext("2d");

      var cx = (- image.cx + 1) / 2.0 * canvas.width - strokeWidth
      var cy = (+ image.cy + 1) / 2.0 * canvas.height - strokeWidth

      ctx.beginPath()
      ctx.arc((cx+1), (cy+1), size, 0, 2 * Math.PI, false)
      if (fill) {
          ctx.fillStyle = fill
          ctx.fill()
      }
      if (stroke) {
          ctx.lineWidth = strokeWidth
          ctx.strokeStyle = stroke
          ctx.stroke()
      }
  }

  function draw_centroid(image, id, color, ps=5){
      var canvas = document.getElementById(id);

      //var data = image.data
      // var size = canvas.width / 64.0 //data.length

      var ctx = canvas.getContext("2d");
      //ctx.clearRect(0, 0, canvas.width, canvas.height);

      var cx = (- image.cx + 1) / 2.0 * canvas.width
      var cy = (+ image.cy + 1) / 2.0 * canvas.height
      ctx.fillStyle = color

      ctx.fillRect((cx)-(ps/2), (cy)-(ps/2), ps, ps)

  }

  function draw_image(image, id, mask=null){

      var canvas = document.getElementById(id);

      var data = image.data
      var dark = image.dark

      // var darkedData = data - dark

      var imgMax = image.max
      var imgMin = image.min
      var totFlux = image.tot_flux

      if(!mask && id!="cloud" ){
          if( $("#subtract-dark").prop("checked")){

              imgMin = image.minDark
              imgMax = image.maxDark
              totFlux = image.tot_flux_darked

          }
      }

      var minmax = update_color_scale(image, imgMin, imgMax, totFlux, id, mask)

      var size_x = canvas.width/data.length
      var size_y = canvas.width/data.length // rectangular

      var ctx = canvas.getContext("2d");

      ctx.imageSmoothingEnabled= false

      /// teccam image
      if (! mask){
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          var myColor = d3.scaleSequential().domain(minmax)
              .interpolator(d3.interpolateViridis);
      } else { /// Gain mask
          if (image.min == image.max){
              var myColor = d3.scaleSequential().domain([image.min, image.max])
                  .range(["rgba(255,255,255,0.0)", "rgba(255,255,255,0.0)"]);

          } else {
              var myColor = d3.scaleSequential().domain([image.min, image.max])
                  .range(["rgba(255,255,255,0.3)", "rgba(255,255,255,0.0)"]);
          }
      }

      var mean_flux = 0;
      for (var x=0; x<data.length; x++) {
          for (var y=0; y<data[0].length; y++) {

              if (!mask && id!="cloud" ){
                  if ($("#subtract-dark").prop("checked")){
                      data[x][y] = data[x][y] - dark[x][y]
                  }
                  mean_flux = mean_flux + (data[x][y])
              }

              var value = data[x][y]
              ctx.fillStyle = myColor(value)

              ctx.fillRect((x)*size_x, (y)*size_y, size_x, size_y);
          }
      }
      if (!mask && id!="cloud" ){
          $("#image-mean_flux-"+id).text( Math.round( mean_flux/Math.pow(data.length,2) ))
      }
  }

  function draw_dm(dm, id, flat=false){

      var dm_min = dm.min
      var dm_max = dm.max
      if (flat){
          dm_min = dm.min_no_flat
          dm_max = dm.max_no_flat
      }
      
      var minmax = update_color_scale(dm, dm_min, dm_max, null, id)
      
      var canvas = document.getElementById(id);
      var size = Math.round(canvas.width / 11)-2 // max actuators in a row: 11. -2 is for separation between squares.

      var ctx = canvas.getContext("2d");
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      /// dm shape

      var myColor = d3.scaleSequential().domain(minmax)
          .interpolator(d3.interpolateBrBG);

      dm.actuators.forEach(function(actuator, i){
          var value = dm.shape[i]
          if (flat)
              value -= dm.flat[i]

          var ay = ((actuator[0]*0.9+0.05) * canvas.width) - (size/2)
          var ax = ((actuator[1]*0.9+0.05) * canvas.height) - (size/2)
          //var ay = (actuator[0] * canvas.width) - (size/2)
          //var ax = (actuator[1] * canvas.height) - (size/2)

          ctx.fillStyle = myColor(value)
          ctx.fillRect(ax, ay, size, size);
          if( $("#show-act-info").prop("checked")){
              ctx.fillStyle = "black"
              ctx.fillText(value.toFixed(2), ax+size/2-size/8, ay+size/2)
              ctx.fillText(i+1, ax+size/2, ay+size/2-size/4)
          }
      })

  }
  
  //////////////
  /// STREAM ///
  //////////////
  
  var source = new EventSource('/web/rtc/stream'); // in rtc.py

  source.onmessage = function(e) {
      var d = JSON.parse(e.data)

      $('[data-status="ref_cx"]').text(d.cred.cx.toFixed(2))
      $('[data-status="ref_cy"]').text(d.cred.cy.toFixed(2))

      $('[data-status="current_cx"]').text(d.cloud.cx.toFixed(2))
      $('[data-status="current_cy"]').text(d.cloud.cy.toFixed(2))

      console.log(d)
      $("#image-skp_cmd-dm").text(d.dm.skp_cmd)
      $("#image-cloud_samples-cloud").text(d.cloud.cloud_samples)
      
      draw_image(d.cred, "cred") // cred image
      draw_image(d.gain, "cred", true ) // mask true
      draw_centroid(d.cred, "cred", "red") // red dot
      draw_circle(d.cloud, "cred", "red", 1) // red circle

      draw_dm(d.dm, "dm", false)
      draw_dm(d.dm, "dm2", true)

      draw_image(d.cloud, "cloud")

      /// Draw a circle corresponding to the center of rotation.
      /// "data" is a dummy array.
      /// "cx" and "cy" are the normalized coordinates
      
      //var center_of_rotation = {data:[1,2,3], cx:+0.28, cy:-0.11}
      var center_of_rotation = {data:[1,2,3], cx:+0.16, cy:+0.04}
      draw_circle(center_of_rotation, "cred", "white", 0.2) // red circle

  }
  


</script>


{% endblock content %}
