/*****************************************************************************
 * 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() {
   $('#addType').jqxDropDownList({
    theme: theme,
    source: DeviceTypeAdapter,
    valueMember: 'mno',
    displayMember: 'en',
    width: 180,
    height: 30,
    autoDropDownHeight: true
   });
   $("#addType").jqxDropDownList('disableItem', "W1" );	/* These are auto created, so disable. */
   $("#addType").jqxDropDownList('disableItem', "GPIO" );
   $("#addType").jqxDropDownList('disableItem', "SIM" );
   $('#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 = 'dbdevices.php',
 source = {
  datatype: 'json',
  cache: false,
  datafields: [
   { name: 'uuid', type: 'string' },
   { name: 'type', type: 'string' },
   { name: 'address', type: 'string' },
   { name: 'subdevice', type: 'int' },
   { name: 'inuse', type: 'int' },
   { name: 'description', type: 'string' },
   { name: 'direction', type: 'string' },
   { name: 'value', type: 'int' },
   { name: 'offset', type: 'int' },
   { name: 'present', type: 'string' },
   { name: 'gpiopin', type: 'int' },
   { name: 'comment', type: 'string' },
   { 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.
 $('#dev_uuid').jqxInput({ theme: theme, width: 360, height: 23 });
 $('#dev_description').jqxInput({ theme: theme, width: 800, height: 23 });
 $('#dev_type').jqxDropDownList({
  theme: theme,
  source: DeviceTypeAdapter,
  valueMember: 'mno',
  displayMember: 'en',
  width: 180,
  height: 23,
  autoDropDownHeight: true
 });
 $('#dev_type').on('select', function (event) {
  var args = event.args;
  if (args) {
    if (args.index == 8) {
      $('#pin_pmpt').html('Domoticz idx:');
      if (parseInt($('#dev_gpiopin').jqxNumberInput('val')) < 0) {
	$('#dev_gpiopin').val(+0);
      }
      $('#dev_gpiopin').show();
      $('#dev_gpiopin').jqxNumberInput(PosInt);
    } else if ((args.index == 2) || (args.index == 3)) {
      $('#pin_pmpt').html('GPIO pin:');
      if (parseInt($('#dev_gpiopin').jqxNumberInput('val')) > 31) {
	$('#dev_gpiopin').val(-1);
      }
      $('#dev_gpiopin').show();
      $('#dev_gpiopin').jqxNumberInput(GPIOInt);
    } else {
      $('#dev_gpiopin').val(0);
      $('#pin_pmpt').html('');
      $('#dev_gpiopin').hide();
      $('#dev_gpiopin').jqxNumberInput(Show0dec);
    }
  }
 });
 $('#dev_direction').jqxDropDownList({
  theme: theme,
  source: DeviceDirectionAdapter,
  valueMember: 'mno',
  displayMember: 'en',
  width: 180,
  height: 23,
  autoDropDownHeight: true
 });
 $('#dev_value').jqxNumberInput(Spin0dec);
 $('#dev_offset').jqxNumberInput(Spin0dec);
 $('#dev_address').jqxInput({ theme: theme, width: 200, height: 23 });
 $('#dev_subdevice').jqxNumberInput(SubInt);
 $('#dev_present').jqxDropDownList({
  theme: theme,
  source: DevicePresentAdapter,
  valueMember: 'mno',
  displayMember: 'en',
  width: 180,
  height: 23,
  autoDropDownHeight: true
 });
 $('#dev_inuse').jqxNumberInput(Show0dec);
 $('#dev_timestamp').jqxInput({ theme: theme, width: 200, height: 23 });
 $('#dev_comment').jqxInput({ theme: theme, width: 800, height: 23 });

 // 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, impButton;
   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;">Nieuw</span></div>');
   container.append(addButton);
   statusbar.append(container);
   addButton.jqxButton({ theme: theme, width: 90, height: 17 });
   // add new row.
   addButton.click(function(event) {
    $('#addType').val('NA');
    $('#addWindow').jqxWindow('open');
    $('#addOk').click(function() {
     if ($('#addType').val() != 'NA') {
      console.log('Add type ' + $('#addType').val());
      var data,
      data = 'add=true&type=' + $('#addType').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');
     } else {
      console.log('Add wrong type');
     }
    });
   });
  },
  columns: [
   { text: 'Address', datafield: 'address', width: 180 },
   { text: 'Sub', datafield: 'subdevice', width: 50 },
   { text: 'Present', datafield: 'present', width: 80 },
   { text: 'Type', datafield: 'type', width: 100 },
   { text: 'Direction', datafield: 'direction', width: 110 },
   { text: 'Value', datafield: 'value', width: 80 },
   { text: 'Used', datafield: 'inuse', width: 60 },
   { text: 'Description', datafield: 'description' },
   { 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: 110, y: 15 } });
     dataRecord = $('#jqxgrid').jqxGrid('getrowdata', editrow);
     $('#dev_uuid').val(dataRecord.uuid);
     $('#dev_description').val(dataRecord.description);
     $('#dev_type').val(dataRecord.type);
     $('#dev_direction').val(dataRecord.direction);
     $('#dev_value').val(dataRecord.value);
     $('#dev_offset').val(dataRecord.offset);
     $('#dev_address').val(dataRecord.address);
     $('#dev_subdevice').val(dataRecord.subdevice);
     $('#dev_present').val(dataRecord.present);
     $('#dev_gpiopin').val(dataRecord.gpiopin);
     $('#dev_inuse').val(dataRecord.inuse);
     var date = new Date((dataRecord.timestamp * 1000) - tzoffset).toISOString().slice(0, 19).replace("T", " ");
     $('#dev_timestamp').val(date);
     $('#dev_comment').val(dataRecord.comment);
     // show the popup window.
     $('#popupWindow').jqxWindow('open');
    }
   }
  ],
 });

 // initialize the popup window and buttons.
 $('#popupWindow').jqxWindow({
  width: 1050,
  height: 625,
  resizable: false,
  theme: theme,
  isModal: true,
  autoOpen: false,
  cancelButton: $('#Cancel'),
  modalOpacity: 0.40
 });
 $('#popupWindow').on('open', function() {
  $('#dev_description').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 = 'del=true&uuid=' + $('#dev_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,
   type: $('#dev_type').val(),
   direction: $('#dev_direction').val(),
   value: parseInt($('#dev_value').jqxNumberInput('decimal')),
   offset: parseInt($('#dev_offset').jqxNumberInput('decimal')),
   present: $('#dev_present').val(),
   address: $('#dev_address').val(),
   subdevice: parseInt($('#dev_subdevice').jqxNumberInput('decimal')),
   gpiopin: parseInt($('#dev_gpiopin').jqxNumberInput('val')),
   description: $('#dev_description').val(),
   comment: $('#dev_comment').val()
  };
  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 == 'device') {
   // Use the message to trigger update.
   $('#jqxgrid').jqxGrid('updatebounddata');
  }
 }
});
