'use strict';

/*
 * *******************************************************************************
 *  * 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
 *  *******************************************************************************
 *
 */

$(document).ready(function () {
  var accTok = apwGetAccessToken();

  catalogLoading();

  getRegistryList();
});

var getElementsCatalog = function getElementsCatalog(accTok) {
  return $.ajax({
    url: fogControllerUrl + ioAuthoring.urls.getElementsForPublish + '?t=' + accTok,
    dataType: 'json'
  });
};

var catalogLoading = function catalogLoading() {
  getElementsCatalog(accTok).then(function (res) {
    getElementLayouts(res.elementCatalog).then(function (result) {
      // <!--Turns on modals-->
      AppWorks_Start();
      $('.modal-trigger').leanModal();
      $('#element-properties-configform').trigger('autoresize');

      activateHandlersForPublishingInterface();
      var element;
      for (var i = 0; i < result.layoutData.length; i++) {
        element = result.layoutData[i];
        createNewElementOnCanvas(element.id, element.name, element.picture, element.isSelected, element.layoutX, element.layoutY);
        activateElementsDraggable(element.id);
        activateElementsClickHandler(element.id);
      }
      var instance = $('.element-container.element-selected');
      var id = instance.attr('data-element-id');
      if (id != undefined) {
        scrollToInstance(instance);
        selectElement(id);
      }
    });
  });
};

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

var getRegistryList = function getRegistryList() {
  $.ajax({
    type: 'GET',
    url: '' + fogControllerUrl + ioAuthoring.urls.getRegistryList + '?t=' + accTok,
    dataType: 'json',
    success: function success(result) {
      if (result.status === 'ok') {
        var el = $('#dockerRegistrySelect');
        el.empty();

        var option = document.createElement('option');
        option.value = 'add';
        option.innerHTML = 'Add new registry...';
        el.append(option);

        result.registry.map(function (reg) {
          var option = document.createElement('option');
          option.value = reg.id;
          option.innerHTML = reg.url;
          el.append(option);
        });
        el.val(window.registry || 1);
        el.material_select();
      }
    }
  });
};