<!--
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved. 
// 
// This file is part of hev-sw.
// 
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
// 
// hev-sw is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public Licence
// for more details.
// 
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
// 
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
-->
{% set logs_active = True %}
{% extends 'base.html' %}


{% block content %}

<style>
  table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 75%;
  }
  
  td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
  }
  
  tr:nth-child(even) {
    background-color: #dddddd;
  }
  </style>

<main>
  <div class="container-fluid">
    <!--<h1 class="mt-4">Info</h1> !-->


    <div class="tab">
      <button class="tablinks" onclick="openTab(this, 'Main',false)">Main</button>
      <button class="tablinks" onclick="openTab(this, 'history',false)">History</button>
      <button class="tablinks" onclick="openTab(this, 'clinicalAlarms',false)">Clinical Alarms</button>
      <button class="tablinks" onclick="openTab(this, 'technicalAlarms',false)">Technical Alarms</button>

    </div>

    <div id="Main" class="tabcontent">

    <!--<input type="button" class="form-control py-2" value="Update alarms" id="update_button"></input>-->
    <!-- <button type="button" class="form-control py-2" id="ack_alarms">Acknowledge all alarms</button> -->


    <table id="active_alarms" class="text-white tiny alarmlog w-100">
      <thead>
          <tr>
              <th>Start Date and time</th>
              <th></th>

              <th>Alarm type</th>
              <th>Alarm code</th>
              <!-- <th>Acknowledgement</th> -->


          </tr>
      </thead>
      <tbody>
          <tr>

          </tr>
      </tbody>
      <tfoot>
          <tr>
              
          </tr>
      </tfoot>
  </table>
</div>
<div id="history" class = "tabcontent">

      <table id="inactive_alarms" class="text-white tiny alarmlog w-100">
        <thead>
            <tr>
                <th>Start Date and time</th>
                <th>End Date and time</th>

                <th>Alarm type</th>
                <th>Alarm code</th>
                <!-- <th>Acknowledgement</th> -->


            </tr>
        </thead>
        <tbody>
            <tr>

            </tr>
        </tbody>
        <tfoot>
            <tr>
                
            </tr>
        </tfoot>
    </table>
  </div>

  <div id="clinicalAlarms" class="tabcontent">
    <form class="settings-form w-100">
      <table class = "ml-auto mr-auto">
        <tr></tr><tr>
          <td><label class="small">APNEA</label></td>
          <td>MIN <input class="form-control py-1 lockable" id="min_APNEA" type="number" value="15" onclick="show_easy_numpad(this, min_APNEA_controller);"/></td>
          <td>MAX <input class="form-control py-1 lockable" id="max_APNEA" type="number" value="0" onclick="show_easy_numpad(this, max_APNEA_controller);"/></td>
          <td><input type="button" class="form-control py-2" value="Submit thresholds" id="APNEA" onclick=submit_thresholds(this)></input></td>
        </tr>
           
        <tr></tr><tr>
          <td><label class="small">CHECK_VALVE_EXHALE</label></td>
          <td>MIN <input class="form-control py-1 lockable" id="min_CHECK_VALVE_EXHALE" type="number" value="0" onclick="show_easy_numpad(this, min_CHECK_VALVE_EXHALE_controller);"/></td>
          <td>MAX <input class="form-control py-1 lockable" id="max_CHECK_VALVE_EXHALE" type="number" value="15" onclick="show_easy_numpad(this, max_CHECK_VALVE_EXHALE_controller);"/></td>
          <td><input type="button" class="form-control py-2" value="Submit thresholds" id="CHECK_VALVE_EXHALE" onclick=submit_thresholds(this)></input></td>
        </tr>            

        <tr></tr><tr>
          <td><label class="small">CHECK_P_PATIENT</label></td>
          <td>MIN <input class="form-control py-1 lockable" id="min_CHECK_P_PATIENT" type="number" value="0" onclick="show_easy_numpad(this, min_CHECK_P_PATIENT_controller);"/></td>
          <td>MAX <input class="form-control py-1 lockable" id="max_CHECK_P_PATIENT" type="number" value="15" onclick="show_easy_numpad(this, max_CHECK_P_PATIENT_controller);"/></td>
          <td><input type="button" class="form-control py-2" value="Submit thresholds" id="CHECK_P_PATIENT" onclick=submit_thresholds(this)></input></td>
        </tr>            

        <tr></tr><tr>
          <td><label class="small">EXPIRATION_SENSE_FAULT_OR_LEAK</label></td>
          <td>MIN <input class="form-control py-1 lockable" id="min_EXPIRATION_SENSE_FAULT_OR_LEAK" type="number" value="1" onclick="show_easy_numpad(this, min_EXPIRATION_SENSE_FAULT_OR_LEAK_controller);"/></td>
          <td>MAX <input class="form-control py-1 lockable" id="max_EXPIRATION_SENSE_FAULT_OR_LEAK" type="number" value="2" onclick="show_easy_numpad(this, max_EXPIRATION_SENSE_FAULT_OR_LEAK_controller);"/></td>
          <td><input type="button" class="form-control py-2" value="Submit thresholds" id="EXPIRATION_SENSE_FAULT_OR_LEAK" onclick=submit_thresholds(this)></input></td>
        </tr>            

      </table>
    </form>      
  </div>


  <div id="technicalAlarms" class="tabcontent">
TO BE ADDED
  </div>


  </div>
</main>

<script>


class input_controller{
	constructor(name, element) {
    this.name = name;
	this.element = element;
  }
  getName(){ return this.name;}
  getValue() {
    return this.element.value;
  }
  setValue(val){
    //e.g.
    window.createNotification({
			closeOnClick: 1,
			displayCloseButton: 0,
			positionClass: "nfc-bottom-right",
			showDuration: false,
			theme: "info"
		})({
			title: "Alarm settings",
			message: "Threshold updated from " + this.element.value + " to " + val + " for " + this.name
	  });
	  this.element.value = val;
    //sendCmd(this.name, val);
  }
  getMin(){
	  if (this.element.min) return this.element.min;
	  else return null;
  }
  getMax(){
	  if (this.element.max) return this.element.max;
	  else return null;
  }
}

min_APNEA_controller = new input_controller("min_APNEA", document.getElementById("min_APNEA"));
max_APNEA_controller = new input_controller("max_APNEA", document.getElementById("max_APNEA"));

min_CHECK_VALVE_EXHALE_controller = new input_controller("min_CHECK_VALVE_EXHALE", document.getElementById("min_CHECK_VALVE_EXHALE"));
max_CHECK_VALVE_EXHALE_controller = new input_controller("max_CHECK_VALVE_EXHALE", document.getElementById("max_CHECK_VALVE_EXHALE"));

min_CHECK_P_PATIENT_controller = new input_controller("min_CHECK_P_PATIENT", document.getElementById("min_CHECK_P_PATIENT"));
max_CHECK_P_PATIENT_controller = new input_controller("max_CHECK_P_PATIENT", document.getElementById("max_CHECK_P_PATIENT"));

min_EXPIRATION_SENSE_FAULT_OR_LEAK_controller = new input_controller("min_EXPIRATION_SENSE_FAULT_OR_LEAK", document.getElementById("min_EXPIRATION_SENSE_FAULT_OR_LEAK"));
max_EXPIRATION_SENSE_FAULT_OR_LEAK_controller = new input_controller("max_EXPIRATION_SENSE_FAULT_OR_LEAK", document.getElementById("max_EXPIRATION_SENSE_FAULT_OR_LEAK"));


var logging;


function convertTimestamp(timestamp) {
  date = new Date(timestamp);
  var h = date.getHours();
	var m = date.getMinutes();
	var s = date.getSeconds();
  return (("0"+date.getDate()).slice(-2)) +"."+ (("0"+(date.getMonth()+1)).slice(-2)) +"."+ (date.getFullYear()) 
         + ' &emsp; ' +	 h + ":" + m + ":" + s; ;
}

//to keep track of last called alarms to check for new ones
var alarmrowid = 0;
/* this is a list of active alarm ROWID so we don't have to replicate the whole thing every time */
var active_alarm_rows  = [];

function requestAlarms() {
  $.getJSON({
      url: '/active-alarms',
      success: function(data) {
        var table = document.getElementById("active_alarms");
        /* keep a list of the latest row ids to check against and remove inactive later */
        var latest_rows = [];
        for (let i = 0 ; i < data.length; i++){
          latest_rows.push(data[i].ROWID);
          if ( active_alarm_rows.includes(data[i].ROWID) ){
            // do nothing, we already are showing the active alarm
          }
          else{
             if (data[i].alarm_code != "") {
              var row = table.insertRow(1);
              row.id = 'active-alarm-'+data[i].ROWID;
              var cell1 = row.insertCell(0);
              var cell2 = row.insertCell(1);
              var cell3 = row.insertCell(2);
              var cell4 = row.insertCell(3);
            
              //cell1.innerHTML = convertTimestamp(data.created_at)
              cell1.innerHTML = convertTimestamp(data[i].start_timestamp);
              //cell2.innerHTML = convertTimestamp(data[i].timestamp);
              //cell2.innerHTML = data[i].ROWID;
              cell3.innerHTML = data[i].alarm_type;            
              cell4.innerHTML = data[i].alarm_code;
              //cell4.innerHTML =  '<button type="button" class="form-control py-2" id="ack"   style="background-color:#1f4793; border-color:blue; color:white">Ack</button>';
              active_alarm_rows.push(data[i].ROWID);
              
           }
         }
        }
        //check if any of the active alarms are not in the latest haul, if not remove
        
        //do this so we can remove after
        var toRemove = [];

        for ( let i = 0 ; i < active_alarm_rows.length; i++ ) {
          var value = active_alarm_rows[i];
          if (!(latest_rows.includes(value))) {
            var elem = document.getElementById("active-alarm-"+value); elem.parentNode.removeChild(elem);
            toRemove.push(value);
          }
        }
        for ( let i = 0 ; i < toRemove.length; i++){
          const index = active_alarm_rows.indexOf(toRemove[i]);
          active_alarm_rows.splice(index, 1);
        }
      },
      cache: false
  });

  $.getJSON({
      url: '/log-alarms/'+alarmrowid,
      success: function(data) {
        var table = document.getElementById("inactive_alarms");
        if (data.length > 0) {
          alarmrowid = data[0].ROWID;
        }
        for (let i = 0 ; i < data.length; i++){
         if (data[i].alarm_code != "") {
            var row = table.insertRow(1);
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            var cell3 = row.insertCell(2);
            var cell4 = row.insertCell(3);


            //cell1.innerHTML = convertTimestamp(data.created_at)
            cell1.innerHTML = convertTimestamp(data[i].start_timestamp);
            cell2.innerHTML = convertTimestamp(data[i].timestamp);
            cell3.innerHTML = data[i].alarm_type;            
            cell4.innerHTML = data[i].alarm_code;
            //cell4.innerHTML =  '<button type="button" class="form-control py-2" id="ack"   style="background-color:#1f4793; border-color:blue; color:white">Ack</button>';
         }
         }
         
      },
      cache: false
  });
   // call it again after one second
   alarmLogs = setTimeout(requestAlarms, 1000);
}

/*
function update_logs() {
    //clearInterval(alarmInterval);
    requestAlarms();
}
*/
var button_state = false;

/*
document.getElementById('update_button').onclick = function(){
  if (button_state == false) {
    this.style.color = "white";
    this.value = "Loading alarms"
    this.style.backgroundColor = "green";
    button_state = true;
    update_logs();
  } else {
    this.style.color = "#383838";
    this.value = "Update alarms"
    this.style.backgroundColor = "white";
    button_state = false;
    clearInterval(alarmLogs);
  }
}
*/


function set_alarm_threshold(var_name, var_min, var_max) {
  var buffer = {name: var_name, min : var_min, max : var_max};
  console.log(buffer);
  $.ajax({
        type: "POST",
        url:"/set_alarm_threshold",
        data: buffer   // converts js value to JSON string
        })    
};

submit_thresholds = function(element){
    minimum_val = document.getElementById("min_"+String(element.id)).value;
    maximum_val = document.getElementById("max_"+String(element.id)).value;
    set_alarm_threshold(element.id, minimum_val, maximum_val);
    // Test
    //alert(minimum_val.value + "  " + maximum_val.value);
}


</script>


{% endblock %}

{% block body_scripts %}
<script>

$(document).ready( function (){
  requestAlarms();
});

function openTab(el, cityName) {
 if (el.disabled && (!force)) return;
 if (el.parentElement.disabled && (!force)) return;
  // Declare all variables
  var i, tabcontent, tablinks;

  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that opened the tab
  document.getElementById(cityName).style.display = "block";
  el.className += " active";
}

$(document).ready ( function(){
  var tablinks = document.getElementsByClassName("tablinks");
  if (tablinks.length > 0){
    openTab(tablinks[0],"Main",true);
  }
  // decide what to unlock based on mode
  //var object = document.getElementById("Trends");
  //var opt = object.options[object.selectedIndex];
});
  /*
  $( document ).ready($.getJSON({
  url: '/last_N_alarms',
  success: function(data) {
    var table = document.getElementById("HEV_logs");
    for (let i = data.length-1; i >= data.length-10; i--) {
      if (data[i]['alarms'] != "none") {
        var row = table.insertRow(1);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        cell1.innerHTML = data[i]['timestamp'];
        cell2.innerHTML = data[i]['alarms'];
      }
    }
  }
  }));
  */
</script>

{% endblock %}
