'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

/*
 * *******************************************************************************
 *  * Copyright (c) 2018 Edgeworx, Inc.
 *  *
 *  * This program and the accompanying materials are made available under the
 *  * terms of the Eclipse Public License v. 2.0 which is available at
 *  * http://www.eclipse.org/legal/epl-2.0
 *  *
 *  * SPDX-License-Identifier: EPL-2.0
 *  *******************************************************************************
 *
 */

var toastDelay = 5000;
var counter = 0;
var gridSize = 20;
var accTok = apwGetAccessToken();

// function addBlueBox() {
//     var token = $('#bluebox-token').val();
//     $.ajax({
//         type: "POST",
//         url: ioAuthoring.urls.addBluebox,
//         dataType: "json",
//         data: {t: accTok, token: token},
//         success: function (result) {
//             // var result = $.parseJSON(response);

//             if(result.status == 'ok')
//             {
//                 location.reload();
//             }
//             else
//             {
//                 alert(result.errormessage);
//                 // if(result.ErrorCode == -4)
//                 // {
//                 //     alert("Registration failed: Unable to create fog instance.");
//                 // } else if(result.ErrorCode == -5)
//                 // {
//                 //     alert("Registration failed: Authentication failed.");
//                 // } else if(result.ErrorCode == -6)
//                 // {
//                 //     alert("Registration failed: Please enter a valid token.");
//                 // }
//             }
//         }
//     });
// }


function activateHandlersForInstances() {
  $('.fog-instance-container').draggable({
    helper: 'original',
    opacity: 0.8,
    delay: 200,
    revert: 'invalid',
    revertDuration: 400,
    scroll: true,
    containment: 'parent',
    zIndex: 99999,
    start: function start(event, ui) {
      $('.fog-canvas').css({ 'overflow-x': '', 'overflow-y': '' });
    },
    stop: function stop(event, ui) {
      $('.fog-canvas').css({ 'overflow-x': 'scroll', 'overflow-y': 'scroll' });
    },
    drag: function drag(event, ui) {
      var topRemainder = ui.position.top % gridSize;
      var leftRemainder = ui.position.left % gridSize;

      if (ui.position.left > 0) {
        ui.position.top = ui.position.top - topRemainder;
        ui.position.left = ui.position.left - leftRemainder;
      }
    }
  });

  $('.fog-canvas').css({ 'overflow-x': 'scroll', 'overflow-y': 'scroll' });
}

function activateHandlersForFogInterface() {
  //Set up the handlers and immediate actions
  $('.fog-type-container').draggable({
    helper: 'clone',
    opacity: 0.8,
    delay: 200,
    revert: 'invalid',
    revertDuration: 400,
    scroll: false,
    zIndex: 99999,
    start: function start(event, ui) {
      $('.fog-toolbox').css({ 'overflow-x': '', 'overflow-y': '' });
    },
    stop: function stop(event, ui) {
      $('.fog-toolbox').css({ 'overflow-x': 'scroll', 'overflow-y': 'scroll' });
    },
    drag: function drag(event, ui) {
      var canvasX = $('.fog-canvas').offset().left;

      var topRemainder = ui.position.top % gridSize;
      var leftRemainder = ui.position.left % gridSize;

      if (ui.position.left > canvasX) {
        ui.position.top = ui.position.top - topRemainder;
        ui.position.left = ui.position.left - leftRemainder;
      }
    }
  });

  $('.fog-canvas').droppable({
    drop: handleFogTypeDropOnCanvas
  });

  //This is a hack to work around a scrolling issue with draggable. We will make the toolbar on the left become
  //scrollable AFTER the draggable handler has been added to the toolbar items.
  $('.fog-toolbox').css({ 'overflow-x': 'scroll', 'overflow-y': 'scroll' });
}

function handleFogTypeDropOnCanvas(event, ui) {
  var canvasX = $('.fog-canvas').offset().left;

  var fogX = ui.position.left;
  var fogY = ui.position.top;

  var posX = Math.floor((fogX - canvasX) / gridSize) * gridSize;
  var posY = Math.floor(fogY / gridSize) * gridSize;

  if (ui.draggable.attr('data-fog-type-id') != undefined) {
    // new instance
    var canvas = $('.fog-canvas');
    var canvasTop = canvas.scrollTop();
    var canvasLeft = canvas.scrollLeft();

    posX += canvasLeft;
    posY += canvasTop;

    counter++;
    var image = ui.draggable.attr('data-fog-type-image');
    var fogType = ui.draggable.attr('data-fog-type-id');
    createNewInstance(posX, posY, counter, image, fogType);
  } else {
    // existing instance
    var id = ui.draggable.attr('data-fog-instance-id');
    updateInstanceLayoutInfo(id, fogX, fogY, true);
    ui.draggable.attr('data-fog-instance-layout-x', fogX);
    ui.draggable.attr('data-fog-instance-layout-y', fogY);
    $('#instance_' + id).css('top', fogY);
    $('#instance_' + id).css('left', fogX);
    selectInstance(id);
  }
}

function createNewInstance(posX, posY, tempId, image, fogType) {
  var name = 'Unnamed ioFog ' + tempId;
  var id = 'TEMP_' + tempId;

  $('.fog-properties-loading-overlay').css('display', 'visible');
  var tmpFog = {
    id: id,
    selected: 1,
    posY: posY,
    posX: posX,
    name: name,
    image: '/images/shared/' + image,
    version: '',
    bluetooth: false,
    debug: false,
    viewer: false,
    statusUpdate: 10,
    getChanges: 20,
    getScan: 60
  };
  createElementOnCanvas(tmpFog);

  $.ajax({
    type: 'POST',
    url: fogControllerUrl + ioAuthoring.urls.createFogInstance,
    dataType: 'json',
    data: { t: accTok, fogType: fogType, name: name, location: '', description: '' },
    success: function success(result) {
      if (result.status == 'ok') {
        activateHandlersForInstances();

        var details = result.instance;
        var instanceId = details.uuid;

        $('#fog-canvas-layout-grid').find('#instance_TEMP_' + tempId).attr('data-fog-instance-id', instanceId);
        $('#fog-canvas-layout-grid').find('#instance_TEMP_' + tempId).attr('id', 'instance_' + instanceId);
        $('#display-name-TEMP_' + tempId).attr('id', 'display-name-' + instanceId);
        $('#name-strong-TEMP_' + tempId).attr('id', 'name-strong-' + instanceId);

        $('#fog-canvas-layout-grid').find('#spinner_' + id).css('display', 'none');
        $('#fog-canvas-layout-grid').find('#spinner_' + id).attr('id', 'spinner_' + instanceId);

        $('.fog-properties-loading-overlay').css('display', 'none');

        updateInstanceLayoutInfo(instanceId, posX, posY, 1);

        counter--;

        if (selectedInstance != undefined && selectedInstance != '') {
          var selectedDiv = $('#instance_' + selectedInstance);
          selectedDiv.attr('data-fog-instance-selected', '0');
          selectedDiv.removeClass('fog-instance-selected');
          updateInstanceLayoutInfo(selectedInstance, selectedDiv.attr('data-fog-instance-layout-x'), selectedDiv.attr('data-fog-instance-layout-y'), 0);
        }

        selectedInstance = instanceId;

        activateInstanceClickHandler();

        fogInstanceClickHandler(instanceId);
        fogHwInfoClickHandler(instanceId);
        fogUsbInfoClickHandler(instanceId);
        dockerContainersInfoClickHandler(instanceId);
      }
    }
  });
}

function activateInstanceClickHandler() {
  $('.fog-instance-container').click(function () {
    var instanceId = $(this).attr('data-fog-instance-id');
    selectInstance(instanceId);
  });
}

function selectInstance(instanceId) {
  var tmp;
  if (selectedInstance != '') {
    tmp = $('#instance_' + selectedInstance);
    tmp.attr('data-fog-instance-selected', '0');
    tmp.removeClass('fog-instance-selected');
    updateInstanceLayoutInfo(selectedInstance, tmp.attr('data-fog-instance-layout-x'), tmp.attr('data-fog-instance-layout-y'), false);
  }
  selectedInstance = instanceId;
  tmp = $('#instance_' + instanceId);
  tmp.attr('data-fog-instance-selected', '1');
  tmp.addClass('fog-instance-selected');
  fogInstanceClickHandler(instanceId);
  fogHwInfoClickHandler(instanceId);
  fogUsbInfoClickHandler(instanceId);
  dockerContainersInfoClickHandler(instanceId);
  updateInstanceLayoutInfo(instanceId, tmp.attr('data-fog-instance-layout-x'), tmp.attr('data-fog-instance-layout-y'), true);
}

function fogInstanceClickHandler(instanceId) {
  $('.fog-properties-loading-overlay').css('display', 'visible');

  $.ajax({
    type: 'POST',
    url: fogControllerUrl + ioAuthoring.urls.getFogDetails,
    dataType: 'json',
    data: { t: accTok, instanceId: instanceId },
    success: function success(result) {
      if (result.status == 'ok') {
        var fog = result.fog[0];

        var durationTimeStamp = Math.floor(fog.DaemonOperatingDuration / 1000);

        var rem = durationTimeStamp % 60;
        var durationStr = rem == 0 ? '00' : rem < 10 ? '0' + rem : rem;

        durationTimeStamp = Math.floor(durationTimeStamp / 60);
        if (durationTimeStamp > 0) {
          rem = durationTimeStamp % 60;
          durationStr = (rem == 0 ? '00' : rem < 10 ? '0' + rem : rem) + ':' + durationStr;

          durationTimeStamp = Math.floor(durationTimeStamp / 60);
          if (durationTimeStamp > 0) {
            durationStr = durationTimeStamp + ':' + durationStr;
          } else {
            durationStr = '00:' + durationStr;
          }
        } else {
          durationStr = '00:00:' + durationStr;
        }

        var diskUsage = fog.DiskUsage * 1;
        var memoryUsage = fog.MemoryUsage * 1;
        var cpuUsage = fog.CPUUsage * 1;

        $('#fog-instance-properties-name').val(fog.Name);
        $('#fog-instance-properties-location').val(fog.Location);
        $('#fog-instance-properties-gpsmode').text(fog.GpsMode);
        $('#fog-instance-properties-lat').val(fog.Latitude);
        $('#fog-instance-properties-lon').val(fog.Longitude);
        $('#fog-instance-properties-description').val(fog.Description);
        $('#fog-instance-properties-bluetooth').prop('checked', fog.Bluetooth == 1 ? true : false);
        $('#fog-instance-properties-docker').prop('checked', fog.IsolatedDockerContainer == 1 ? true : false);
        $('#fog-instance-properties-hal').prop('checked', fog.hal == 1 ? true : false);
        $('#fog-instance-properties-mongo').prop('checked', fog.mongo == 1 ? true : false);
        $('#fog-instance-properties-influx').prop('checked', fog.influx == 1 ? true : false);
        $('#fog-instance-properties-grafana').prop('checked', fog.grafana == 1 ? true : false);

        $('#fog-instance-properties-instanceid').text(fog.UUID);
        $('#fog-instance-properties-ipaddress').text(fog.IPAddress);
        $('#fog-instance-properties-lastactive').text(new Date(fog.LastActive * 1).toUTCString());
        $('#fog-instance-properties-systemtime').text(new Date(fog.SystemTime * 1).toUTCString());
        $('#fog-instance-properties-laststatustime').text(new Date(fog.LastStatusTime * 1).toUTCString());
        $('#fog-instance-properties-lastcomandtime').text(new Date(fog.LastCommandTime * 1).toUTCString());
        $('#fog-instance-properties-fogtypename').text(fog.typeName);
        if (fog.LastStatusTime * 1 < new Date().getTime() - 60000) $('#fog-instance-properties-daemonstatus').text('UNKNOWN');else $('#fog-instance-properties-daemonstatus').text(fog.DaemonStatus);
        $('#fog-instance-properties-daemonoperatingduration').text(durationStr);
        $('#fog-instance-properties-daemonlaststarttime').text(new Date(fog.DaemonLastStart * 1).toUTCString());
        $('#fog-instance-properties-processedmessages').text(fog.ProcessedMessages);
        $('#fog-instance-properties-diskusage').text(diskUsage.toFixed(3) + ' GiB');
        $('#fog-instance-properties-memoryusage').text(memoryUsage.toFixed(3) + ' MiB');
        $('#fog-instance-properties-cpuusage').text(cpuUsage.toFixed(2) + '%');

        $('#fog-instance-properties-networkinterface').text(fog.NetworkInterface);
        $('#fog-instance-properties-dockerurl').val(fog.DockerURL);
        $('#fog-instance-properties-disklimit').val(fog.DiskLimit);
        $('#fog-instance-properties-diskdirectory').val(fog.DiskDirectory);
        $('#fog-instance-properties-memorylimit').val(fog.MemoryLimit);
        $('#fog-instance-properties-cpulimit').val(fog.CPULimit);
        $('#fog-instance-properties-logdirectory').val(fog.LogDirectory);
        $('#fog-instance-properties-logdisklimit').val(fog.LogLimit);
        $('#fog-instance-properties-logfilecount').val(fog.LogFileCount);
        $('#fog-instance-properties-getChanges').val(fog.ChangeFrequency);
        $('#fog-instance-properties-getScan').val(fog.ScanFrequency);
        $('#fog-instance-properties-statusUpdate').val(fog.StatusFrequency);

        $('#fog-instance-properties-provisioningkey').text('-');

        setProxyStatus(fog.Proxy);
        setProxyButton(fog.Proxy);

        $('#fog-instance-properties-version').text(fog.Version);
        processVersionUpgradePossibility(fog.isReadyToUpgrade);
        processVersionRollbackPossibility(fog.isReadyToRollback);
      }
      $('.fog-properties-loading-overlay').css('display', 'none');
    }
  });
}

function recursiveAddInfoElements(elementSelector, elementObj, isChild, paddingLevel) {
  if (isChild) paddingLevel++;

  if (elementObj != null) {
    if (elementObj.length) {
      elementObj.map(function (objElement) {
        addElement(objElement, isChild, paddingLevel, elementSelector);
      });
    } else {
      addElement(elementObj, isChild, paddingLevel, elementSelector);
    }
  }
}

function addElement(obj, isChild, paddingLevel, elementSelector) {
  Object.keys(obj).map(function (key) {
    try {
      obj[key] = JSON.parse(obj[key]);
    } catch (e) {} finally {
      if (_typeof(obj[key]) === 'object') {
        createInfoElement(elementSelector, key, isChild, paddingLevel + 1);

        recursiveAddInfoElements(elementSelector, obj[key], true, paddingLevel);
      } else {
        var element = createInfoInnerElement(key);

        var infoElement = document.createElement('span');
        infoElement.innerHTML = obj[key];

        element.appendChild(infoElement);

        if (!isChild) {
          var rowElement = createInfoRowElement();

          rowElement.appendChild(element);
          $(elementSelector).append(rowElement);
        } else {
          $(elementSelector).children().last().append(element);
        }
      }
    }
  });
}

function createInfoElement(elementSelector, elementName, isChild, paddingLevel) {
  var element = createInfoInnerElement(elementName, isChild, paddingLevel);

  $(elementSelector).append(element);
}

function createInfoRowElement() {
  var rowElement = document.createElement('div');
  rowElement.classList.add('row');

  return rowElement;
}

function createInfoInnerElement(elementName, isChild, paddingLevel) {
  var element = document.createElement('div');
  element.classList.add('row');
  element.classList.add('col');
  element.classList.add('s12');
  element.style.marginBottom = 'auto';
  if (isChild && paddingLevel) element.style.paddingLeft = paddingLevel * 10 + 'px';
  element.innerHTML = elementName[0].toUpperCase() + elementName.slice(1) + ': ';

  return element;
}

function fogHwInfoClickHandler(instanceId) {
  $.ajax({
    type: 'POST',
    url: fogControllerUrl + ioAuthoring.urls.getFogHWInfo,
    dataType: 'json',
    data: { t: accTok, instanceId: instanceId },
    success: function success(result) {
      if (result.status == 'ok') {
        var fogHwInfoObj = result.fog;

        if (fogHwInfoObj != null) {
          $('#hw-info-element').empty();
          recursiveAddInfoElements('#hw-info-element', fogHwInfoObj, false, 0);
        }
      }
    }
  });
}

function fogUsbInfoClickHandler(instanceId) {
  $.ajax({
    type: 'POST',
    url: fogControllerUrl + ioAuthoring.urls.getFogUSBInfo,
    dataType: 'json',
    data: { t: accTok, instanceId: instanceId },
    success: function success(result) {
      if (result.status == 'ok') {
        var fogUsbInfoObj = result.fog;

        if (fogUsbInfoObj != null) {
          recursiveAddInfoElements('#usb-info-element', fogUsbInfoObj, false);
        }
      }
    }
  });
}

function dockerContainersInfoClickHandler(instanceId) {
  $.ajax({
    type: 'POST',
    url: fogControllerUrl + ioAuthoring.urls.listElementInstanceWithStatus,
    dataType: 'json',
    data: { t: accTok, instanceId: instanceId },
    success: function success(result) {
      if (result.status == 'ok') {
        var infoObj = result.list;

        if (infoObj != null) {
          $('#docker-container-info-element').children().remove();
          recursiveAddInfoElements('#docker-container-info-element', infoObj, false);
        }
      }
    }
  });
}

function setProxyStatus(proxyStr) {
  if (proxyStr) {
    var proxy = JSON.parse(proxyStr);
    $('#proxy-instance-properties-username').text(proxy.username);
    $('#proxy-instance-properties-host').text(proxy.host);
    $('#proxy-instance-properties-lport').text(proxy.lport);
    $('#proxy-instance-properties-rport').text(proxy.rport);
    $('#proxy-instance-properties-status').text(proxy.status);
    $('#proxy-instance-properties-errors').text(proxy.errormessage);
  } else {
    $('#proxy-instance-properties-username').text('-');
    $('#proxy-instance-properties-host').text('-');
    $('#proxy-instance-properties-lport').text(0);
    $('#proxy-instance-properties-rport').text(0);
    $('#proxy-instance-properties-status').text('CLOSED');
    $('#proxy-instance-properties-errors').text('-');
  }
}

function setProxyButton(proxyStr) {
  if (!proxyStr) {
    showOpenProxyButton();
  } else {
    var proxy = JSON.parse(proxyStr);
    if (proxy.status == 'OPEN') {
      showCloseProxyButton();
    } else if (proxy.status == 'PENDING_OPEN') {
      $('#proxy-close-button').hide();
      $('#proxy-open-button').show();
      $('#proxy-open-button').attr('disabled', true);
      $('#proxy-open-button').addClass('disabled');
    } else if (proxy.status == 'PENDING_CLOSE') {
      $('#proxy-open-button').hide();
      $('#proxy-close-button').show();
      $('#proxy-close-button').attr('disabled', true);
      $('#proxy-close-button').addClass('disabled');
    } else {
      showOpenProxyButton();
    }
  }
}

function showOpenProxyButton() {
  $('#proxy-close-button').hide();
  $('#proxy-open-button').show();
  $('#proxy-open-button').attr('disabled', false);
  $('#proxy-open-button').removeClass('disabled');
}

function showCloseProxyButton() {
  $('#proxy-open-button').hide();
  $('#proxy-close-button').show();
  $('#proxy-close-button').attr('disabled', false);
  $('#proxy-close-button').removeClass('disabled');
}

function processVersionUpgradePossibility(isReady) {
  if (isReady === 1) {
    $('#version-upgrade-button').prop('disabled', false).show();
  } else {
    $('#version-upgrade-button').prop('disabled', true).hide();
  }
}

function processVersionRollbackPossibility(isReady) {
  if (isReady === 1) {
    $('#version-rollback-button').prop('disabled', false).show();
  } else {
    $('#version-rollback-button').prop('disabled', true).hide();
  }
}

function updateInstanceLayoutInfo(instanceId, layoutX, layoutY, isSelected) {
  $.ajax({
    type: 'POST',
    url: ioAuthoring.urls.updateFogInstanceLayout,
    dataType: 'json',
    data: { instanceId: instanceId, layoutX: layoutX, layoutY: layoutY, selected: isSelected == true ? 1 : 0 },
    success: function success(result) {}
  });
}

function getProvisioningKey(instanceId) {
  $.ajax({
    type: 'GET',
    url: fogControllerUrl + ioAuthoring.urls.fogProvisioning + instanceId,
    dataType: 'json',
    data: {},
    success: function success(result) {
      if (result.status == 'ok') {
        var key = result.provisionKey;
        $('#fog-instance-properties-provisioningkey').text(key);
      }
    },
    error: function error(result) {
      $('#fog-instance-properties-provisioningkey').text('error');
    }
  });
}

function setupChangeMonitors() {
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-name' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-location' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-lat' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-lon' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-description' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-dockerurl' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-disklimit' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-diskdirectory' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-memorylimit' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-cpulimit' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-logdirectory' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-logdisklimit' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-logfilecount' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-statusUpdate' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-getChanges' });
  $(document).apwInputChangeMonitor({ 'targetElement': 'fog-instance-properties-getScan' });
  $('input[type=text]').blur(function () {
    updateInstanceSetting();
  });
  $('#fog-instance-properties-bluetooth').change(updateInstanceSetting);
  $('#fog-instance-properties-docker').change(updateInstanceSetting);
  $('#fog-instance-properties-hal').change(updateInstanceSetting);
  $('#fog-instance-properties-mongo').change(updateInstanceSetting);
  $('#fog-instance-properties-influx').change(updateInstanceSetting);
  $('#fog-instance-properties-grafana').change(updateInstanceSetting);
}

function deleteFogInstance(instanceId) {
  $.ajax({
    type: 'POST',
    url: fogControllerUrl + ioAuthoring.urls.deleteFogInstance,
    dataType: 'json',
    data: { t: accTok, instanceId: instanceId },
    success: function success(result) {
      if (result.status == 'ok') {
        deleteFogLayouts(result.instanceId).then(function (res) {
          $('.fog-instance-selected').remove();
          selectedInstance = '';
          var instance = $('.fog-instance-container');
          var id = instance.attr('data-fog-instance-id');
          if (id != undefined) {
            scrollToInstance(instance);
            selectInstance(id);
          } else {
            $('#fog-instance-properties-name').val('');
            $('#fog-instance-properties-location').val('');
            $('#fog-instance-properties-gpsmode').text('');
            $('#fog-instance-properties-lan').val('');
            $('#fog-instance-properties-lot').val('');
            $('#fog-instance-properties-description').val('');

            $('#fog-instance-properties-instanceid').text('-');
            $('#fog-instance-properties-ipaddress').text('-');
            $('#fog-instance-properties-lastactive').text('-');
            $('#fog-instance-properties-systemtime').text('-');
            $('#fog-instance-properties-laststatustime').text('-');
            $('#fog-instance-properties-lastcomandtime').text('-');
            $('#fog-instance-properties-fogtypename').text('-');
            $('#fog-instance-properties-daemonstatus').text('-');
            $('#fog-instance-properties-daemonoperatingduration').text('-');
            $('#fog-instance-properties-daemonlaststarttime').text('-');
            $('#fog-instance-properties-processedmessages').text('-');
            $('#fog-instance-properties-diskusage').text('-');
            $('#fog-instance-properties-memoryusage').text('-');
            $('#fog-instance-properties-cpuusage').text('-');

            $('#fog-instance-properties-networkinterface').text('-');
            $('#fog-instance-properties-dockerurl').val('-');
            $('#fog-instance-properties-disklimit').val('-');
            $('#fog-instance-properties-diskdirectory').val('-');
            $('#fog-instance-properties-memorylimit').val('-');
            $('#fog-instance-properties-cpulimit').val('-');
            $('#fog-instance-properties-logdirectory').val('-');
            $('#fog-instance-properties-logdisklimit').val('-');
            $('#fog-instance-properties-logfilecount').val('-');
            $('#fog-instance-properties-statusUpdate').val('-');
            $('#fog-instance-properties-getChanges').val('-');
            $('#fog-instance-properties-getScan').val('-');
            $('#fog-instance-properties-version').text('-');
            $('#proxy-instance-properties-username').text('-');
            f;
            $('#proxy-instance-properties-host').text('-');
            $('#proxy-instance-properties-rport').text('0');
            $('#proxy-instance-properties-lport').text('0');
            $('#proxy-instance-properties-status').text('CLOSED');
            $('#proxy-instance-properties-errors').text('-');
          }
        });
      }
    }
  });
}

function openSshTunnel(instanceId) {

  var username = $('#input-proxy-username').val();
  var password = $('#input-proxy-password').val();
  var host = $('#input-proxy-address').val();
  var rport = $('#input-proxy-remote-port').val();
  var lport = $('#input-proxy-local-port').val();
  var rsakey = $('#input-proxy-rsa-key').val();

  $.ajax({
    type: 'POST',
    url: fogControllerUrl + ioAuthoring.urls.openSshTunnel,
    dataType: 'json',
    data: {
      t: accTok,
      instanceId: instanceId,
      username: username,
      password: password,
      host: host,
      rport: rport,
      lport: lport,
      rsakey: rsakey
    },
    success: function success(result) {
      if (result.status === 'ok') {
        $('#proxy-open-button').attr('disabled', true);
        $('#proxy-open-button').addClass('disabled');
        console.log('Attempt to open ssh tunnel.');
      }
    }
  });
}

function closeSshTunnel(instanceId) {
  $.ajax({
    type: 'POST',
    url: fogControllerUrl + ioAuthoring.urls.closeSshTunnel,
    dataType: 'json',
    data: {
      t: accTok,
      instanceId: instanceId
    },
    success: function success(result) {
      if (result.status === 'ok') {
        $('#proxy-close-button').attr('disabled', true);
        $('#proxy-close-button').addClass('disabled');
        console.log('attempt to close ssh tunnel');
      }
    }
  });
}

function changeIoFogVersion(instanceId, command) {
  console.log(instanceId);
  console.log(command);
  $.ajax({
    type: 'POST',
    url: fogControllerUrl + ioAuthoring.urls.changeVersion,
    dataType: 'json',
    data: {
      t: accTok,
      instanceId: instanceId,
      versionCommand: command
    }
  });
}

var deleteFogLayouts = function deleteFogLayouts(instanceId) {
  return $.ajax({
    type: 'POST',
    url: ioAuthoring.urls.deleteFogInstanceLayout,
    dataType: 'json',
    data: { instanceId: instanceId },
    success: function success(result) {}
  });
};

function updateInstanceSetting() {
  var instanceId = $('.fog-instance-selected').attr('data-fog-instance-id');
  if (instanceId == null || instanceId == '') return;

  var name = $('#fog-instance-properties-name').val();

  if (name.trim() == '') {
    Materialize.toast('Fog name is empty!', 5000);
    $('#fog-instance-properties-name').focus();
    return;
  }

  var location = $('#fog-instance-properties-location').val();
  var lat = $('#fog-instance-properties-lat').val();
  var lon = $('#fog-instance-properties-lon').val();
  var description = $('#fog-instance-properties-description').val();
  var eth = $('#fog-instance-properties-networkinterface').text();
  if (eth.trim() == '') {
    Materialize.toast('Network interface is empty!', 5000);
    $('#fog-instance-properties-networkinterface').focus();
    return;
  }
  var docker = $('#fog-instance-properties-dockerurl').val();
  if (docker.trim() == '') {
    Materialize.toast('Docker URL is empty!', 5000);
    $('#fog-instance-properties-dockerurl').focus();
    return;
  }
  var diskLimit = $('#fog-instance-properties-disklimit').val();
  if (diskLimit.trim() == '' || isNaN(diskLimit) || diskLimit < 1 || diskLimit > 1048576) {
    Materialize.toast('Disk usage limit is not a valid number between 1 and 1048576 GiB!', 5000);
    $('#fog-instance-properties-disklimit').focus();
    return;
  }
  var diskDir = $('#fog-instance-properties-diskdirectory').val();
  if (diskDir.trim() == '') {
    Materialize.toast('Storage directory is empty!', 5000);
    $('#fog-instance-properties-diskdirectory').focus();
    return;
  }
  var memLimit = $('#fog-instance-properties-memorylimit').val();
  if (memLimit.trim() == '' || isNaN(memLimit) || memLimit < 128 || memLimit > 1048576) {
    Materialize.toast('Memory usage is not a valid number between 128 and 1048576!', 5000);
    $('#fog-instance-properties-memorylimit').focus();
    return;
  }
  var cpuLimit = $('#fog-instance-properties-cpulimit').val();
  if (cpuLimit.trim() == '' || isNaN(cpuLimit) || cpuLimit < 5 || cpuLimit > 100) {
    Materialize.toast('CPU usage limit is not a valid number between 5 and 100!', 5000);
    $('#fog-instance-properties-cpulimit').focus();
    return;
  }
  var logDir = $('#fog-instance-properties-logdirectory').val();
  if (logDir.trim() == '') {
    Materialize.toast('Log file directory is empty!', 5000);
    $('#fog-instance-properties-logdirectory').focus();
    return;
  }
  var logLimit = $('#fog-instance-properties-logdisklimit').val();
  if (logLimit.trim() == '' || isNaN(logLimit) || logLimit < 0.5 || logLimit > 1024) {
    Materialize.toast('Log disk limit is not a valid number between 0.5 and 1024 GiB!', 5000);
    $('#fog-instance-properties-logdisklimit').focus();
    return;
  }
  var logCount = $('#fog-instance-properties-logfilecount').val();
  if (logCount.trim() == '' || isNaN(logCount) || logCount < 1 || logCount > 100 || Math.floor(logCount) != logCount) {
    Materialize.toast('Log file count is not a valid number between 1 and 100!', 5000);
    $('#fog-instance-properties-logfilecount').focus();
    return;
  }

  var statusUpdate = $('#fog-instance-properties-statusUpdate').val();
  if (statusUpdate.trim() == '' || isNaN(statusUpdate) || statusUpdate < 1 || Math.floor(statusUpdate) != statusUpdate) {
    Materialize.toast('Status update frequency is not a valid number greater than 1!', 5000);
    $('#fog-instance-properties-statusUpdate').focus();
    return;
  }

  var getChanges = $('#fog-instance-properties-getChanges').val();
  if (getChanges.trim() == '' || isNaN(getChanges) || getChanges < 1 || Math.floor(getChanges) != getChanges) {
    Materialize.toast('Get changes frequency is not a valid number greater than 1!', 5000);
    $('#fog-instance-properties-getChanges').focus();
    return;
  }
  var getScan = $('#fog-instance-properties-getScan').val();
  if (getScan.trim() == '' || isNaN(getScan) || getScan < 1 || Math.floor(getScan) != getScan) {
    Materialize.toast('Scan Freq is not a valid number greater than 1!', 5000);
    $('#fog-instance-properties-getScan').focus();
    return;
  }

  var bluetooth = $('#fog-instance-properties-bluetooth').is(':checked') ? true : false;
  var isolatedDockerContainer = $('#fog-instance-properties-docker').is(':checked') ? true : false;
  var hal = $('#fog-instance-properties-hal').is(':checked') ? true : false;
  var mongo = $('#fog-instance-properties-mongo').is(':checked') ? true : false;
  var influx = $('#fog-instance-properties-influx').is(':checked') ? true : false;
  var grafana = $('#fog-instance-properties-grafana').is(':checked') ? true : false;
  var reboot = $('.fog-instance-container.fog-instance-selected').attr('fog-instance-reboot') === 'true' ? true : false;
  $('.fog-instance-container.fog-instance-selected').attr('fog-instance-reboot', false);
  $.ajax({
    type: 'POST',
    url: fogControllerUrl + ioAuthoring.urls.fogSettingsUpdate,
    dataType: 'json',
    data: {
      t: accTok,
      instanceId: instanceId,
      name: name,
      description: description,
      location: location,
      lat: lat,
      lon: lon,
      networkInterface: eth,
      dockerUrl: docker,
      diskLimit: diskLimit,
      diskDirectory: diskDir,
      memoryLimit: memLimit,
      cpuLimit: cpuLimit,
      logLimit: logLimit,
      logDirectory: logDir,
      logFileCount: logCount,
      statusFrequency: statusUpdate,
      changeFrequency: getChanges,
      scanFrequency: getScan,
      bluetooth: bluetooth ? 1 : 0,
      debug: 0,
      viewer: 0,
      docker: isolatedDockerContainer ? 1 : 0,
      hal: hal ? 1 : 0,
      mongo: mongo ? 1 : 0,
      influx: influx ? 1 : 0,
      grafana: grafana ? 1 : 0,
      reboot: reboot ? 1 : 0
    },
    success: function success(result) {
      if (result.status == 'ok') {
        setObjectName(instanceId, name);
      }
    }
  });

  // $('input[type=text]').each(function() {
  //     var changed = $(this).attr('apwChanged');
  //     if (changed != 'N') {
  //         alert('changed');
  //     }
  // });
}

function scrollToInstance(instance) {
  var canvas = $('.fog-canvas');

  var canvasTop = canvas.scrollTop();
  var canvasLeft = canvas.scrollLeft();

  var elementTop = instance.attr('data-fog-instance-layout-y');
  var elementLeft = instance.attr('data-fog-instance-layout-x');

  if ((elementTop < canvasTop || elementTop > canvas[0].offsetHeight) && (elementLeft < canvasLeft || elementLeft > canvas[0].offsetWidth)) canvas.animate({ scrollTop: Math.max(elementTop - 50, 0), scrollLeft: Math.max(elementLeft - 50, 0) }, 'slow');else if (elementTop < canvasTop || elementTop > canvas[0].offsetHeight) canvas.animate({ scrollTop: Math.max(elementTop - 50, 0) }, 'slow');else if (elementLeft < canvasLeft || elementLeft > canvas[0].offsetWidth) canvas.animate({ scrollLeft: Math.max(elementLeft - 50, 0) }, 'slow');
}

function setObjectName(id, name) {
  var i = 0;
  var displayName = name;
  var tmp = document.getElementById('name-strong-' + id);
  if (tmp != undefined) $(tmp).remove();
  while (true) {
    var p = document.getElementById('display-name-' + id);
    var t = document.createTextNode(displayName);
    var s = document.createElement('strong');
    var sp = document.createElement('span');
    $(sp).attr('id', 'name-span-' + id);
    $(s).attr('id', 'name-strong-' + id);
    s.appendChild(t);
    p.appendChild(s);
    p.appendChild(sp);
    var pLeft = $(p).offset().left;
    var pHeight = $(p).outerHeight();
    var sLeft = $(sp).offset().left;
    i++;
    displayName = name.substring(0, name.length - i) + '...';
    if (sLeft - pLeft <= 148 && pHeight < 25) {
      $(sp).remove();
      break;
    }
    $(s).remove();
    $(sp).remove();
  }
  p.style.display = '';
}

function createElementOnCanvas(fog) {
  var iofogVersion = fog.version == undefined ? '' : fog.version;

  if (iofogVersion != '' && parseFloat(iofogVersion) < parseFloat(IOFABRIC_VERSION)) {
    Materialize.toast('ioFog service for ' + fog.name + ' is not up to date', toastDelay);
    var backgoundColor = ' style="BACKGROUND-COLOR:#C00000" ';
  }

  var element = '<div class="fog-instance-container ' + (fog.selected == 1 ? 'fog-instance-selected' : '') + '" ' + 'style="top:' + fog.posY + 'px; left:' + fog.posX + 'px;" data-fog-instance-id="' + fog.id + '" id="instance_' + fog.id + '" data-fog-instance-name="' + fog.name + '" data-fog-instance-bluetooth="' + fog.bluetooth + '" data-fog-instance-statusUpdate="' + fog.statusUpdate + '" data-fog-instance-getChanges="' + fog.getChanges + '" data-fog-instance-getScan="' + fog.getScan + '" data-fog-instance-layout-x="' + fog.posX + '" data-fog-instance-layout-y="' + fog.posY + '" data-fog-instance-selected="' + fog.selected + '" xmlns="http://www.w3.org/1999/html"><img class="fog-instance-icon" src="' + fog.image + '?' + new Date().getTime() + '"><p ' + backgoundColor + ' id="display-name-' + fog.id + '"><strong id="name-strong-' + fog.id + '">' + fog.name + '</strong></p><div style="display:none;" class="fog-instance-loading-spinner" id="spinner_' + fog.id + '"><div class="sk-child sk-bounce1"></div><div class="sk-child sk-bounce2"></div><div class="sk-child sk-bounce3"></div></div></div>';
  $('#fog-canvas-layout-grid').append(element);
}

function loadInstances() {
  return $.ajax({
    type: 'POST',
    url: fogControllerUrl + ioAuthoring.urls.fogInstancesList,
    dataType: 'json',
    data: { t: accTok },
    success: function success(result) {
      if (result.status == 'ok') {
        var uuids = _.pluck(result.instances, 'UUID');
        getFogLayout(uuids).then(function (res) {
          var instances = result.instances;
          for (var i = 0; i < instances.length; i++) {
            var instance = instances[i];
            var layoutsData = _.findWhere(res.layoutData, { instanceId: instance.UUID });
            var fog = {
              selected: layoutsData ? layoutsData.isSelected : 0,
              posY: layoutsData ? layoutsData.layoutY : 0,
              posX: layoutsData ? layoutsData.layoutX : 0,
              id: instance.UUID,
              name: instance.Name,
              image: '/images/shared/' + instance.typeImage,
              version: instance.version,
              bluetooth: instance.bluetooth,
              debug: instance.debug,
              viewer: instance.viewer,
              statusUpdate: instance.StatusFrequency,
              getChanges: instance.ChangeFrequency,
              getScan: instance.ScanFrequency
            };
            createElementOnCanvas(fog);
          }

          activateHandlersForInstances();
          activateInstanceClickHandler();

          //Activate dynamically generated handlers for non-optimal stuff
          $('.fog-type-container').each(function (i, div) {
            var id = $(this).attr('data-fog-type-id');
            var last = $('#fog-type-hover-icon-' + id).attr('last');
            $(document).apwHoverPopUp({
              'hoverablesSelector': '#fog-type-hover-icon-' + id,
              'width': 300,
              'height': 300,
              'offsetLeft': 60,
              'offsetTop': last == 0 ? -124 : -225,
              'border': 'N',
              'borderColor': '#ccc',
              'solidBackground': 'Y',
              'backgroundColor': '#eceff1',
              'fillFromID': 'fog-type-description-' + id,
              'hoverPosition': 'right'
            });
          });

          var instance = $('.fog-instance-container.fog-instance-selected');
          var id = instance.attr('data-fog-instance-id');
          if (id != undefined) {
            scrollToInstance(instance);
            selectInstance(id);
          }
        });
      }
    }
  });
};

var apwManualPostUpFailedBlank = function apwManualPostUpFailedBlank() {};
var getFogLayout = function getFogLayout(uuids) {
  return $.ajax({
    type: 'POST',
    url: ioAuthoring.urls.getFogLayout,
    dataType: 'json',
    data: { uuids: uuids },
    success: function success(res) {}
  });
};