{% extends "layouts/base.html" %}

{% block title %} SDOF {% endblock %} 

{% block stylesheets %}  
  <!-- Fonts -->
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link
    href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,600;0,700;1,300;1,400;1,600;1,700&display=swap"
    rel="stylesheet">

{% if False %}
  <link rel="stylesheet" type="text/css" href="./css/mystyles.css" media="screen">
  <link rel="stylesheet" type="text/css" href="./css/slider.css" media="screen">
{% endif %}

  <script type="text/javascript" src="{{ ASSETS_ROOT }}/js/uPlot.iife.min.js"></script>
  <script src="https://unpkg.com/mathjs@10.1.0/lib/browser/math.js"></script>      

  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sdof@0.1.1/wasm/fsdof.js"></script>
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sdof@0.1.1/wasm/index.js"></script>
  <script type="text/javascript" src="{{ ASSETS_ROOT }}/js/fmkFunctions.js"></script>
  <link type="text/css" media="screen" href="{{ ASSET_ROOT }}/css/uPlot.min.css" >
<style>
.slidecontainer {
    width: 100%;
}
.tick, .axis {
  font-size:14px;
}
.select-container {
  /* position: relative;
  margin-top:8px; */
}
.select-css {
     display: block; 
     float: left;
     font-family: inherit;
     /* font-weight: 700; */
     /* color: #444; */
     /* line-height: 1.3; */
     padding: 0px 42px 0 12px;
     /* width: 100%; */
     max-width: 100%; 
     box-sizing: border-box;
     /* height:36px; */
     margin: 0;
     border: 2px solid #919191;
     /* box-shadow: 0 1px 0 1px rgba(0,0,0,.04); */
     border-radius: 4px;
     -moz-appearance: none;
     -webkit-appearance: none;
     appearance: none;
     background-color: #fff;
}
.select-css::-ms-expand {
  /* display: none; */
}
.select-css:focus {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}
</style>

{% endblock stylesheets %}

{% block scripts %}
  <script type="text/javascript" src="./wasm/fsdof.js"></script>
  <script type="text/javascript" src="./wasm/index.js"></script>
{% endblock %}


{% block content %}

    <h1><code>{{ event_data.motions.0.components.0.record_identifier }}</code></h1>
    <div class="introduction">
      <p id="introText"> </p>
    </div>
    
    <div class="interactive-main">
      <div class="form-controls">
        <!-- <fieldset> -->
          <div class="row form-group">
            <fieldset>
              <label for="setExpectation">Expectation</label>
              <div class="select-container">
                <select id="setExpectation"
                        name="method"
                        class="select-css"
                        onchange="setDirectionOptions('setExpectation', 'expectDirection')"
                        aria-controls="plotRegion">
                {% for motion in event_data.motions %}
                  <option value="{{ forloop.counter0 }}">{{ motion.key }}</option>
                {% endfor %}
                </select>
              </div>
              <!-- <label for="expectDirection">Direction</label> -->
              <div class="select-container">
                <select id="expectDirection"
                        name="method"
                        class="select-css"
                        onchange="draw()"
                        aria-controls="plotRegion">
                </select>
              </div>
            </fieldset>
          </div>

          <br>

          <div class="form-group">
            <fieldset>
            <label for="setRecord">Integration Input</label>
            <div class="select-container">
              <select id="setRecord"
                      name="method"
                      class="select-css"
                      onchange="setDirectionOptions('setRecord', 'inputDirection')"
                      aria-controls="plotRegion">
              {% for motion in event_data.motions %}
                <option value="{{ forloop.counter0 }}">{{ motion.key }}</option>
              {% endfor %}
              </select>
            </div>
            <!-- <label for="inputDirection">Direction</label> -->
            <div class="select-container">
              <select id="inputDirection"
                      name="method"
                      class="select-css"
                      onchange="setInputMotion()"
                      aria-controls="plotRegion">
              </select>
            </div>
            </fieldset>
          </div>
          
          <div class="form-group">
            <label for="Tn">Natural Period, Tn: <span id="TnOutput">1.00</span> sec.</label>
            <input id="Tn"
                   type="range"
                   min="0.01"
                   max="1.5"
                   step=".01"
                   oninput="integrate()"
                   value="1.0"
                   class="slider"
                   aria-controls="plotRegion">
          </div>

          <div class="form-group">
            <label for="Z" id="labelZ">Damping Ratio:</label> 
            <input id="Z" type="range" min="0" max="10" step="1" oninput="integrate()" value="2" class="slider"
              aria-controls="plotRegion">
          </div>
          <!-- </fieldset> -->
      </div>
      
      <div class="card p-2">
        <figure>
          <div id="myDiv" class=""></div>
          <figcaption style="font-size:16px;" id="theTextDescription">Figure: Deformation Response of SDOF system.</figcaption> 
        </figure>
      </div>
      <div id="my-chart"></div>

    </div>      
    <p id="check-spoken"> </p>
<!-- Copyright fmckenna@berkeley.edu -->
{% endblock %}

<script>
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
    const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))
</script>

{% block javascripts %}
  <script>
    function plot(xs, vals) {
      let data = [
        xs,
        vals,
        xs.map((t, i) => vals[i]),
        // xs.map((t, i) => vals[i]),
      ];
      const width = 950 - margin.left - margin.right;
      const height = 450  - margin.top - margin.bottom;    
      const opts = {
        width: width,
        height: height,
        title: "Displacements",
        scales: {x: {time: true}},
        hooks: {
          addSeries: [
            (u, seriesIdx) => {
              console.log("addSeries" + (u.status == 0 ? " (init)" : ""), seriesIdx);
            }
          ],
          delSeries: [
            (u, seriesIdx) => {
              console.log("delSeries", seriesIdx);
            }
          ],
        },
        series: [
          {},
          {
            stroke: "red",
            // fill: "rgba(255,0,0,0.1)",
          },
          {
            stroke: "blue",
            // fill: "rgba(0,255,0,0.1)",
          },
          // {
          //   stroke: "blue",
          //   // fill: "rgba(0,0,255,0.1)",
          // },
        ],
      };

      document.querySelector(".uplot")?.remove();
      let u = new uPlot(opts, data, document.querySelector("#myDiv"));
      document.querySelector(".u-under").remove();
      return [u, data];
    }

    function linspace (a, b, n) {
      if (typeof n === 'undefined') n = Math.max(Math.round(b - a) + 1, 1)
      if (n < 2) {
        return n === 1 ? [a] : []
      }
      var i,ret = Array(n);
      n--
      for (i = n;i >= 0;i--) {
        ret[i] = (i * b + (n - i) * a) / n;
      }
      return ret;
    }
    </script>



  <script>
    //
    // Variables: tMax, colors, chart dimensions, and margins
    //
    var sin  = Math.sin;
    var cos  = Math.cos;
    var sqrt = Math.sqrt;
    var abs  = Math.abs;
    var exp  = Math.exp;

    
    const width = 950 - margin.left - margin.right;
    const height = 450  - margin.top - margin.bottom;    

    var tFinal = 30.0;
    var rMax = 5.0;

    const EVENT_DATA =  {{ event_data|safe }};

    var G_InputDirection = 0;
    var G_ExpectDirection = 0;

    var motion_data = EVENT_DATA.motions[0].components[G_InputDirection];

    const PI = 3.14159;
    const g = 980.0;

    var [FIG, DATA] = [null, null];
    var [timeArray, inputMotion] = [null, null];

 
    // 
    // main function to draw the response, called init and when sliders move
    //
    function setInputMotion() {
      var recordName = document.getElementById("setRecord").value;

      G_InputDirection = document.getElementById("inputDirection").value;

      if (EVENT_DATA.motions[recordName])
        motion_data = EVENT_DATA.motions[recordName].components[G_InputDirection];

      inputMotion = motion_data.accel.data; // new Array(timeArray.length);
      let time_step = motion_data.accel.time_step; 
      var dt = time_step;
      var loadLength = motion_data.accel.data.length;
      var tFinal = time_step * loadLength;
      timeArray = linspace(0., tFinal, loadLength);
      // [FIG,DATA] = plot(timeArray, motion_data.displ.data);
      draw();
    }

    function setDirectionOptions(motionID, elemID) {
        var motionID = document.getElementById(motionID).value;        

        var expectedName = document.getElementById("setExpectation").value;        
        
        var selector = document.getElementById(elemID);
        
        // clear current options
        while (selector.options.length > 0) {                
            selector.remove(0);
        }
        
        for (let i=0; i<EVENT_DATA.motions[motionID].components.length; i++) {
            const component = EVENT_DATA.motions[motionID].components[i];
            var opt = document.createElement("option");
            opt.value = i;
            opt.text  = component.component;
            selector.appendChild(opt);
        }
        
    }

    function draw() {
        //
        // get slider values,update their output
        //
        var expectedName = document.getElementById("setExpectation").value;        
        G_ExpectDirection = document.getElementById("expectDirection").value;

        if (EVENT_DATA.motions[expectedName]) {
          var expected = EVENT_DATA.motions[expectedName].components[G_ExpectDirection];
          [FIG,DATA] = plot(timeArray, expected.displ.data);
        } else {
          [FIG,DATA] = plot(timeArray, motion_data.displ.data);
        }

    }

    function logslider(position) {
      const minp = 0.01;
      const maxp = 1.5;

      const minv = Math.log(0.01);
      const maxv = Math.log(1.5);

      // calculate adjustment factor
      var scale = (maxv-minv) / (maxp-minp);

      return Math.exp(minv + scale*(position-minp));
    }

    function integrate() {
        //
        // some constants
        //
        var u0 = 0.;
        var v0 = 0.;
        var m = 1.0;
        
        //
        //  determine some parameters
        //
        var TnNode = document.querySelector('#Tn');
        let Tn = Number(TnNode.value);
        Tn = logslider(Tn).toPrecision(5);
        TnNode.parentNode.querySelector('#TnOutput').textContent = Tn;
        
        var zeta = Number(document.querySelector('#Z')?.value);
        document.getElementById('labelZ').innerHTML = "Damping Ratio, &#120577: "+ zeta + " %";

        var wn = 2 * PI / Tn;
        var k = wn * wn * m;

        if (zeta == 1.0)
            zeta = 0.999999999;

        var c = 2 * m * wn * zeta / 100.;
        
        //
        // Time Series
        //
        let dt = motion_data.accel.time_step; 
        let loadLength = motion_data.accel.data.length;
        let appliedLoad = new Array(timeArray.length);
        
        let n = Math.min(timeArray.length, inputMotion.length);

        for (let i = 0; i < n; i++)
            appliedLoad[i] = -m * inputMotion[i];

        for (let i = n; i < Math.max(timeArray.length, inputMotion.length); i++)
            appliedLoad[i] = 0.0;
        
        var responseDamped = Newmark(m, c, k, u0, v0, dt, appliedLoad, 0.5, 1./6.);
        // FIG.delSeries(2);
        // DATA.splice(2,1);
        // FIG.addSeries({},2);
        DATA.splice(2, 0, responseDamped);
        FIG.setData(DATA);
        
    }

    //
    // draw initial
    //
    setDirectionOptions('setExpectation', 'expectDirection');
    setDirectionOptions('setRecord', 'inputDirection');
    setInputMotion();
    draw();

  </script>
{% endblock javascripts %}

