/*****************************************************************************
 * Copyright (C) 2024
 *
 * Michiel Broek <mbroek at mbse dot eu>
 *
 * This file is part of mbsePi-apps
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * BrewCloud 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 License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ThermFerm; see the file COPYING.  If not, write to the Free
 * Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
 *****************************************************************************/


function createDelElements() {
 $('#eventWindow').jqxWindow({
  theme: theme,
  position: { x: 430, y: 210 },
  width: 420,
  height: 175,
  resizable: false,
  isModal: true,
  modalOpacity: 0.4,
  okButton: $('#delOk'),
  cancelButton: $('#delCancel'),
  initContent: function() {
   $('#delOk').jqxButton({ template: 'danger', width: '65px', theme: theme });
   $('#delCancel').jqxButton({ template: 'success', width: '65px', theme: theme });
   $('#delCancel').focus();
  }
 });
 $('#eventWindow').jqxWindow('hide');
}


function createAddElements() {
 $('#addWindow').jqxWindow({
  theme: theme,
  position: { x: 400, y: 210 },
  width: 480,
  height: 180,
  resizable: false,
  isModal: true,
  modalOpacity: 0.4,
  okButton: $('#addOk'),
  cancelButton: $('#addCancel'),
  initContent: function() {
   $('#addOk').jqxButton({ template: 'success', width: '65px', theme: theme });
   $('#addCancel').jqxButton({ template: 'primary', width: '65px', theme: theme });
   $('#addCancel').focus();
  }
 });
 $('#addWindow').jqxWindow('hide');
}



$(document).ready(function() {
 var dataRecord = {},
 url = 'dbsimulators.php',
 source = {
  datatype: 'json',
  cache: false,
  datafields: [
   { name: 'uuid', type: 'string' },
   { name: 'name', type: 'string' },
   { name: 'simno', type: 'int' },
   { name: 'volume_air', type: 'int' },
   { name: 'volume_beer', type: 'int' },
   { name: 'room_tempaddress', map: 'room>tempaddress' },
   { name: 'room_temperature', map: 'room>temperature', type: 'float' },
   { name: 'room_humaddress', map: 'room>humaddress' },
   { name: 'room_humidity', map: 'room>humidity', type: 'float' },
   { name: 'air_address', map: 'air>address' },
   { name: 'air_temperature', map: 'air>temperature', type: 'float' },
   { name: 'air_present', map: 'air>present' },
   { name: 'beer_address', map: 'beer>address' },
   { name: 'beer_temperature', map: 'beer>temperature', type: 'float' },
   { name: 'beer_present', map: 'beer>present' },
   { name: 'beer_address2', map: 'beer2>address' },
   { name: 'beer_temperature2', map: 'beer2>temperature', type: 'float' },
   { name: 'beer_present2', map: 'beer2>present' },
   { name: 'chiller_address', map: 'chiller>address' },
   { name: 'chiller_temperature', map: 'chiller>temperature', type: 'float' },
   { name: 'chiller_present', map: 'chiller>present' },
   { name: 'cooler_address', map: 'cooler>address' },
   { name: 'cooler_temp', map: 'cooler>temperature', type: 'float' },
   { name: 'cooler_time', map: 'cooler>time', type: 'int' },
   { name: 'cooler_size', map: 'cooler>size', type: 'float' },
   { name: 'cooler_present', map: 'cooler>present' },
   { name: 'cooler_power', map: 'cooler>power', type: 'int' },
   { name: 'heater_address', map: 'heater>address' },
   { name: 'heater_temp', map: 'heater>temperature', type: 'float' },
   { name: 'heater_time', map: 'heater>time', type: 'int' },
   { name: 'heater_size', map: 'heater>size', type: 'float' },
   { name: 'heater_present', map: 'heater>present' },
   { name: 'heater_power', map: 'heater>power', type: 'int' },
   { name: 'fan_address', map: 'fan>address' },
   { name: 'fan_present', map: 'fan>present' },
   { name: 'fan_power', map: 'fan>power', type: 'int' },
   { name: 'light_address', map: 'light>address' },
   { name: 'light_present', map: 'light>present' },
   { name: 'light_power', map: 'light>power', type: 'int' },
   { name: 'door_address', map: 'door>address' },
   { name: 'door_present', map: 'door>present' },
   { name: 'door_value', map: 'door>value', type: 'int' },
   { name: 'psu_address', map: 'psu>address' },
   { name: 'psu_present', map: 'psu>present' },
   { name: 'psu_value', map: 'psu>value', type: 'int' },
   { name: 'frigo_isolation', type: 'float' },
   { name: 'timestamp', type: 'int' }
  ],
  id: 'uuid',
  url: url
 },
 dataAdapter = new $.jqx.dataAdapter(source),
 editrow = -1,
 tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds

 // initialize the input fields.
 $('#name').jqxInput({ theme: theme, width: 240, height: 23 });
 $('#simno').jqxNumberInput(Show0dec);
 $('#uuid').jqxInput({ theme: theme, width: 360, height: 23 });
 $('#room_temperature,#room_humidity').jqxNumberInput(Perc1dec);
 $('#volume_air,#volume_beer').jqxNumberInput(PosInt);
 $('#frigo_isolation').jqxNumberInput(Spin3dec);
 $('#timestamp').jqxInput({ theme: theme, width: 180, height: 23 });

 $('#air_address,#beer_address,#beer_address2,#chiller_address,#cooler_address,#heater_address,#fan_address,#light_address,#door_address,#psu_address').jqxInput({ theme: theme, width: 180, height: 23 });
 $('#air_temperature,#beer_temperature,#beer_temperature2,#chiller_temperature').jqxNumberInput(Show4dec);
 $('#air_present,#beer_present,#beer_present2,#chiller_present,#cooler_present,#heater_present,#fan_present,#light_present,#door_present,#psu_present').jqxDropDownList({
  theme: theme,
  source: DevicePresentAdapter,
  valueMember: 'mno',
  displayMember: 'en',
  width: 180,
  height: 23,
  autoDropDownHeight: true
 });
 $('#cooler_power,#heater_power,#fan_power,#light_power').jqxNumberInput(Perc0);
 $('#cooler_temp,#heater_temp').jqxNumberInput(Spin1dec);
 $('#cooler_time,#heater_time').jqxNumberInput(PosInt);
 $('#cooler_size,#heater_size').jqxNumberInput(Spin4dec);
 $('#door_value').jqxSwitchButton({ height: 23, width: 120, theme: theme, onLabel:'Closed', offLabel: 'Open' });
 $('#psu_value').jqxSwitchButton({ height: 23, width: 120, theme: theme });

 // initialize jqxGrid
 $('#jqxgrid').jqxGrid({
  width: 1280,
  height: 630,
  source: dataAdapter,
  theme: theme,
  showstatusbar: true,
  renderstatusbar: function(statusbar) {
   var rowCount = $("#jqxgrid").jqxGrid('getrows').length;
   statusbar.append('<div style="float: left; margin: 8px; color: orange !important;">Total items: ' + rowCount + '</div>');
   var container, addButton;
   container = $('<div style="overflow: hidden; position: relative; margin: 5px;"></div>');
   addButton = $('<div style="float: right; margin-right: 15px;"><img style="position: relative; margin-top: 2px;" ' +
     'src="images/add.png"/><span style="margin-left: 4px; position: relative; top: -4px;">New</span></div>');
   container.append(addButton);
   statusbar.append(container);
   addButton.jqxButton({ theme: theme, width: 90, height: 17 });
   // add new row.
   addButton.click(function(event) {
    $('#addWindow').jqxWindow('open');
    $('#addName').jqxInput({ theme: theme, width: 180, height: 23 });
    $('#addOk').click(function() {
     var data,
     data = 'add=true&name=' + $('#addName').val();
     console.log(data);
     $.ajax({
      dataType: 'json',
      url: url,
      cache: false,
      data: data,
      type: 'POST',
      success: function(data) {
       if (data.error) {
        console.log('add: ' + data.msg);
        alert('Error: ' + data.msg);
       } else {
        console.log('add: success');
       }
      },
      error: function(jqXHR, textStatus, errorThrown) {}
     });
     $('#jqxgrid').jqxGrid('updatebounddata');
    });
   });
  },
  columns: [
   { text: 'Name', datafield: 'name' },
   { text: 'No.', datafield: 'simno', width: 60 },
   { text: 'Air temp', datafield: 'air_temperature', width: 100, cellsformat: 'f3' },
   { text: 'Beer temp', datafield: 'beer_temperature', width: 100, cellsformat: 'f3' },
   { text: 'Chiller', datafield: 'chiller_temperature', width: 100, cellsformat: 'f3' },
   { text: 'Heater', datafield: 'heater_power', width: 80 },
   { text: 'Cooler', datafield: 'cooler_power', width: 80 },
   { text: 'Fan', datafield: 'fan_power', width: 80 },
   { text: 'Light', datafield: 'light_power', width: 80 },
   { text: 'Door', datafield: 'door_value', width: 60 },
   { text: 'PSU', datafield: 'psu_value', width: 60 },
   { text: 'Last change', datafield: 'timestamp', width: 190,
     cellsrenderer: function(index, datafield, value, defaultvalue, column, rowdata) {
      var date = new Date((value * 1000) - tzoffset).toISOString().slice(0, 19).replace("T", " ");
      return '<span style="margin: 3px; margin-top: 6px; float: left;">' +  date + '</span>';
    }
   },
   { text: '', datafield: 'Edit', width: 100, align: 'center', columntype: 'button', cellsrenderer: function() {
    return 'Edit';
    }, buttonclick: function(row) {
     // open the popup window when the user clicks a button.
     editrow = row;
     $('#popupWindow').jqxWindow({ position: { x: 40, y: 15 } });
     dataRecord = $('#jqxgrid').jqxGrid('getrowdata', editrow);
     $('#name').val(dataRecord.name);
     $('#uuid').val(dataRecord.uuid);
     $('#simno').val(dataRecord.simno);
     $('#room_temperature').val(dataRecord.room_temperature);
     $('#room_humidity').val(dataRecord.room_humidity);
     $('#volume_air').val(dataRecord.volume_air);
     $('#volume_beer').val(dataRecord.volume_beer);
     $('#frigo_isolation').val(dataRecord.frigo_isolation);

     $('#air_address').val(dataRecord.air_address);
     $('#air_temperature').val(dataRecord.air_temperature);
     $('#air_present').val(dataRecord.air_present);
     $('#beer_address').val(dataRecord.beer_address);
     $('#beer_temperature').val(dataRecord.beer_temperature);
     $('#beer_present').val(dataRecord.beer_present);
     $('#beer_address2').val(dataRecord.beer_address2);
     $('#beer_temperature2').val(dataRecord.beer_temperature2);
     $('#beer_present2').val(dataRecord.beer_present2);
     $('#chiller_address').val(dataRecord.chiller_address);
     $('#chiller_temperature').val(dataRecord.chiller_temperature);
     $('#chiller_present').val(dataRecord.chiller_present);
     $('#cooler_address').val(dataRecord.cooler_address);
     $('#cooler_power').val(dataRecord.cooler_power);
     $('#cooler_present').val(dataRecord.cooler_present);
     $('#cooler_temp').val(dataRecord.cooler_temp);
     $('#cooler_time').val(dataRecord.cooler_time);
     $('#cooler_size').val(dataRecord.cooler_size);
     $('#heater_address').val(dataRecord.heater_address);
     $('#heater_power').val(dataRecord.heater_power);
     $('#heater_present').val(dataRecord.heater_present);
     $('#heater_temp').val(dataRecord.heater_temp);
     $('#heater_time').val(dataRecord.heater_time);
     $('#heater_size').val(dataRecord.heater_size);
     $('#fan_address').val(dataRecord.fan_address);
     $('#fan_power').val(dataRecord.fan_power);
     $('#fan_present').val(dataRecord.fan_present);
     $('#light_address').val(dataRecord.light_address);
     $('#light_power').val(dataRecord.light_power);
     $('#light_present').val(dataRecord.light_present);
     $('#door_address').val(dataRecord.door_address);
     $('#door_value').val(dataRecord.door_value);
     $('#door_present').val(dataRecord.door_present);
     $('#psu_address').val(dataRecord.psu_address);
     $('#psu_value').val(dataRecord.psu_value);
     $('#psu_present').val(dataRecord.psu_present);
     var date = new Date((dataRecord.timestamp * 1000) - tzoffset).toISOString().slice(0, 19).replace("T", " ");
     $('#timestamp').val(date);
     // show the popup window.
     $('#popupWindow').jqxWindow('open');
    }
   }
  ],
 });

 // initialize the popup window and buttons.
 $('#popupWindow').jqxWindow({
  width: 1280,
  height: 625,
  resizable: false,
  theme: theme,
  isModal: true,
  autoOpen: false,
  cancelButton: $('#Cancel'),
  modalOpacity: 0.40
 });
 $('#popupWindow').on('open', function() {
  $('#name').jqxInput('selectAll');
 });
 $('#Delete').jqxButton({ template: 'danger', width: '90px', theme: theme });
 $('#Delete').click(function() {
  // Open a popup to confirm this action.
  $('#eventWindow').jqxWindow('open');
  $('#delOk').click(function() {
   var data,
   data = 'del=true&uuid=' + $('#uuid').val();
   $.ajax({
    dataType: 'json',
    url: url,
    cache: false,
    data: data,
    type: 'POST',
    success: function(data) {
     if (data.error) {
      console.log('del: ' + data.msg);
      alert('Error: ' + data.msg);
     } else {
      console.log('del: success');
     }
    },
    error: function(jqXHR, textStatus, errorThrown) {}
   });
   $('#jqxgrid').jqxGrid('updatebounddata');
  });
  $('#popupWindow').jqxWindow('hide');
 });
 $('#Cancel').jqxButton({ template: 'primary', width: '90px', theme: theme });
 $('#Save').jqxButton({ template: 'success', width: '90px', theme: theme });
 $('#Save').click(function() {
  var data,
  row = {
   uuid: dataRecord.uuid,
   name: $('#name').val(),
   volume_air:  parseInt($('#volume_air').jqxNumberInput('decimal')),
   volume_beer: parseInt($('#volume_beer').jqxNumberInput('decimal')),
   room_temperature: parseFloat($('#room_temperature').jqxNumberInput('decimal')),
   room_humidity: parseFloat($('#room_humidity').jqxNumberInput('decimal')),
   air_present: $('#air_present').val(),
   beer_present: $('#beer_present').val(),
   beer_present2: $('#beer_present2').val(),
   chiller_present: $('#chiller_present').val(),
   cooler_temp: parseFloat($('#cooler_temp').jqxNumberInput('decimal')),
   cooler_time: parseInt($('#cooler_time').jqxNumberInput('decimal')),
   cooler_size: parseFloat($('#cooler_size').jqxNumberInput('decimal')),
   cooler_present: $('#cooler_present').val(),
   cooler_power: parseInt($('#cooler_power').jqxNumberInput('decimal')),
   heater_temp: parseFloat($('#heater_temp').jqxNumberInput('decimal')),
   heater_time: parseInt($('#heater_time').jqxNumberInput('decimal')),
   heater_size: parseFloat($('#heater_size').jqxNumberInput('decimal')),
   heater_present: $('#heater_present').val(),
   heater_power: parseInt($('#heater_power').jqxNumberInput('decimal')),
   fan_present: $('#fan_present').val(),
   fan_power: parseInt($('#fan_power').jqxNumberInput('decimal')),
   light_present: $('#light_present').val(),
   light_power: parseInt($('#light_power').jqxNumberInput('decimal')),
   door_present: $('#door_present').val(),
   door_value: $('#door_value').val(),
   psu_present: $('#psu_present').val(),
   psu_value: $('#psu_value').val(),
   frigo_isolation: parseFloat($('#frigo_isolation').jqxNumberInput('decimal'))
  };
  data = 'update=true&' + $.param(row);
  console.log(data);
  $.ajax({
   dataType: 'json',
   url: url,
   cache: false,
   data: data,
   type: 'POST',
   success: function(data) {
    if (data.error) {
     console.log('update: ' + data.msg);
     alert('Error: ' + data.msg);
    } else {
     console.log('update: success');
     $('#jqxgrid').jqxGrid('updatebounddata');
    }
   },
   error: function(jqXHR, textStatus, errorThrown) {}
  });
  $('#popupWindow').jqxWindow('hide');
 });
 createDelElements();
 createAddElements();

 websocket.onmessage = function(evt) {
  var msg = evt.data;
  var obj = JSON.parse(msg);

  if (obj.ping) {
   websocket.send('{"pong":' + obj.ping + '}');
  }

  if (obj.type == 'simulator') {
   // Use the message to trigger update.
   $('#jqxgrid').jqxGrid('updatebounddata');
  }
 }
});
