'use strict';
define(function() {
  var treeBranchPicker = function(ngDialog) {
    var buildTree = function(data, depth, selector) {
      depth = depth || 1;
      selector = selector || '';

      var editTree = [];
      data.forEach(function(d, idx) {
        var selectorbis = selector == '' ? '' + idx : selector + '#' + idx;

        var element = {
          label: d.label,
          children: [],
          level: depth,
          selector: selectorbis,
        };

        if (d.children.length > 0) {
          var sub = buildTree(d.children, depth + 1, selectorbis);
          sub.forEach(function(s) {
            element.children.push(s);
          });
        }
        editTree.push(element);
      });

      return editTree;
    };

    return {
      templateUrl:
        'js/XG/widgets/utilities/form/views/treeBranchPickerButton.html',
      restrict: 'E',
      scope: {
        picked: '=?',
        tree: '=?',
      },
      controller: [
        '$scope',
        function($scope) {
          $scope.treectrl = {};
        },
      ],
      link: function(scope, element, attrs, ctrl) {
        scope.pickTree = angular.copy(scope.tree);

        if (angular.isArray(scope.pickTree)) {
          scope.pickTree = buildTree(scope.pickTree);
        } else {
          scope.pickTree = false;
        }

        scope.openTreeBranchPicker = function() {
          ngDialog.open({
            template:
              'js/XG/widgets/utilities/form/views/treeBranchPicker.html',
            className: 'ngdialog-theme-plain width600 nopadding miniclose',
            closeByDocument: false,
            scope: scope,
          });
        };

        scope.selectBranch = function(branch) {
          scope.picked = "'" + branch.selector + "'";
        };
      },
    };
  };

  treeBranchPicker.$inject = ['ngDialog'];
  return treeBranchPicker;
});
