'use strict';
define(function() {
  var gcelement = function(gclayers, gcStyleFactory, $timeout) {
    return {
      templateUrl: 'js/XG/widgets/utilities/form/views/formTabRender.html',
      restrict: 'A',
      scope: {
        map: '=map',
        fti: '=fti',
        res: '=res',
        feattree: '=treeControl',
        initvalue: '=initvalue',
        templatetab: '=templatetab',
        editable: '=',
        currentbranch: '=',
        dropped: '=',
        formvariables: '=',
        uploadfile: '=',
        removedfile: '=',
        dlgPopup: '='
      },
      link: function(scope) {


        /**
         * Toggle tab edit mode
         * @param mode
         */
        scope.toggleTabEditMode = function(mode) {
          scope.editMode = mode;
        };
        /**
         * Remove a tab
         * @param mode
         */
        scope.removeTab = function(index) {
          scope.templatetab.tabs.splice(index, 1);
        };

        /**
         * Move a tab
         * @param mode
         */
        scope.switchedTab = -1;
        scope.moveTab = function(index, direction) {
          if (
            (index == 0 && direction == 'left') ||
            (index == scope.templatetab.tabs.length - 1 && direction == 'right')
          )
            return false;
          var newTabs = angular.copy(scope.templatetab.tabs),
            newIndex = direction == 'left' ? index - 1 : index + 1;
          newTabs.splice(index, 0, newTabs.splice(newIndex, 1)[0]);
          scope.templatetab.tabs = newTabs;
          scope.switchedTab = newIndex;
          // KIS-3340: le déplacement d'un onglet doit garder le focus sur cet onglet
          $timeout(() => {
            scope.templatetab.activeTab = newIndex;
          })
        };

        scope.$watch('templatetab.activeTab', function(x) {
          if (x == -1) {
            $timeout(function() {
              if (scope.switchedTab != -1) {
                scope.templatetab.activeTab = scope.switchedTab;
                scope.switchedTab = -1;
              }
            }, 0);
          }
        });
      },
    };
  };

  gcelement.$inject = ['gclayers', 'gcStyleFactory', '$timeout'];
  return gcelement;
});
