'use strict';
define(function() {
  var verticaltoolbardirective = function(
    $compile,
    $window,
    $timeout,
    $interval,
    $rootScope,
    UsersFactory
  ) {
    return {
      templateUrl: 'js/XG/containers/views/verticaltoolbar.html',
      restrict: 'A',
      replace: true,
      link: function(scope) {
        var toolvarsNames = {};
        scope.currenttbbuttonname = '';
        scope.$watch(
          function() {
            return scope.toolsbarbutton;
          },
          function(buttons) {
            var toolbar = angular.element(
              document.getElementById('gcverticaltoolbar')
            );
            toolbar.empty();

            if (!buttons.length) return;

            angular.forEach(scope.toolsbarbutton, function(tool, key) {
              var hasRole = true;

              if ($rootScope.xgos.user.name != 'root') {
                if (angular.isDefined(tool.roles)) {
                  if (tool.roles.length > 0) {
                    hasRole = false;

                    angular.forEach($rootScope.xgos.user.roles, function(ro) {
                      var deleteIndex = tool.roles
                        .map(function(x) {
                          return x;
                        })
                        .indexOf(ro.name);

                      if (deleteIndex > -1) {
                        hasRole = true;
                      }
                    });
                  }
                }
              }

              if (tool.type == 'widget' && hasRole) {
                toolvarsNames[tool.name] = tool;
                var ind,
                  toolName = tool.name;
                ind = toolName.indexOf('#');
                if (ind != -1) {
                  toolName = toolName.substring(0, ind);
                }
                var direct;
                if (tool.title == 'toolbarselectiontools.tbtooltip')
                  direct =
                    '<div  class="toolbar_button" id="' +
                    tool.name +
                    '" ' +
                    toolName +
                    '></div>';
                else if (angular.isUndefined(tool.title)) {
                  direct =
                    '<div  class="toolbar_button" ng-click="onclickevent(\'' +
                    tool.name +
                    '\')" id="' +
                    tool.name +
                    '" ' +
                    toolName +
                    '></div>';
                } else {
                  direct =
                    '<div  class="toolbar_button" ng-click="onclickevent(\'' +
                    tool.name +
                    '\')" id="' +
                    tool.title +
                    '" ' +
                    toolName +
                    '></div>';
                }

                var templateScope = scope.$new();
                templateScope.config = tool.config;
                templateScope.params = tool.params;
                templateScope.toolBarWidget = tool;
                templateScope.onclickevent = function(a) {

                  if (a != scope.currenttbbuttonname) {
                    scope.$broadcast(
                      'closeToolsBar_' + scope.currenttbbuttonname,
                      scope.currenttbbuttonname
                    );
                    scope.currenttbbuttonname = a;

                    // log user activity
                    UsersFactory.user_monitoring({
                      sector: $rootScope.xgos.sector,
                      path: 'map',
                      category: 'map_tool',
                      parameters: '[Ouverture][' + a + ']',
                    });
                  } else {
                    scope.currenttbbuttonname = '';
                  }

                  /**
                   * [Permet de désactiver les boutons de scrolls lorsqu'un outil est ouvert.]
                   * [Se base sur les boutons enfants direct de la vertical toolbar.]
                   */

                  //				scope.$broadcast('checkinfotoolbar');
                };
                var a = $compile(direct)(templateScope);
                toolbar.append(a);
              }
            });
          },
          true
        );


        const toolsBar = $("#gcverticaltoolbar")[0];
        // ------ Scroll sidebar --------------

        let scrollUpInterval;
        let scrollDownInterval;

        scope.startScrollUp = () => {
          scope.stopScrollUp();
          scrollUpInterval = $interval(() => {
            if (toolsBar.scrollTop > 0) {
              toolsBar.scrollTop -= 1;
            }
          }, 5);
        };
    
        scope.stopScrollUp = () => {
          $interval.cancel(scrollUpInterval);
        };
    
        scope.startScrollDown = () => {
          scope.stopScrollDown();
          scrollDownInterval = $interval(function() {
            if (toolsBar.scrollTop < (toolsBar.scrollHeight - toolsBar.clientHeight)) {
              toolsBar.scrollTop += 2;
            }
          }, 5);
        };

        scope.stopScrollDown = () => {
          $interval.cancel(scrollDownInterval);
        };

        // évalue si la barre peut être scrollée vers le bas
        scope.canScrollDown = () => {
          if (toolsBar) {
            return !((toolsBar.scrollHeight - toolsBar.clientHeight) >= Math.ceil(toolsBar.scrollTop) - 1
              && (toolsBar.scrollHeight - toolsBar.clientHeight) <= Math.ceil(toolsBar.scrollTop) + 1);
          }
        };

        // évalue si la barre peut être scrollée vers le haut
        scope.canScrollUp = () => {
          if (toolsBar) {
            return toolsBar.scrollTop !== 0;
          }
        };

        scope.$on('checkinfotoolbar', function() {
          $timeout(function() {
            var buttonActive = angular.element(
              document.getElementsByClassName('toolbarscroll')
            );
            var disabled = false;
            var clickedButton = angular.element(
              document
                .getElementById('gcverticaltoolbar')
                .getElementsByClassName('toolbar_button')
            );
            if (clickedButton !== []) {
              for (var i = clickedButton.length - 1; i >= 0; i--) {
                if (
                  angular
                    .element(clickedButton[i].firstElementChild)
                    .hasClass('btn-info') &&
                  disabled === false
                ) {
                  disabled = true;
                }
              }
              if (disabled === true) {
                buttonActive.addClass('disabledScroll');
              } else {
                disabled = false;
                buttonActive.removeClass('disabledScroll');
              }
            }
          }, 500);
        });
      },
    };
  };

  verticaltoolbardirective.$inject = [
    '$compile',
    '$window',
    '$timeout',
    '$interval',
    '$rootScope',
    'UsersFactory',
  ];
  return verticaltoolbardirective;
});
