import _ from 'lodash';

export default function sortableSelect($compile) {
  return {
    restrict: 'E',
    templateUrl: '/js/xivo/directives/sortable-select.html',
    replace: true,
    scope: {
      label: '@',
      list: '=',
      selected: '=',
      error: '='
    },
    link: (scope, element) => {
      scope.sortableOptions = {
        connectWith: '.section-sortable .list-sortable',
        placeholder: "section-ph"
      };
      element.find("ul").attr("ui-sortable","sortableOptions");
      $compile(element.contents())(scope);

      const switchItem = (array1, array2, item) => {
        array1.push(_.remove(array2, { 'id': item.id}).pop());
      };

      scope.add = (item) => {
        switchItem(scope.selected, scope.list, item);
      };

      scope.remove = (item) => {
        switchItem(scope.list, scope.selected, item);
      };

      scope.addAll = () => {
        angular.copy(scope.list).forEach(item => {
          scope.add(item);
        });
      };

      scope.removeAll = () => {
        angular.copy(scope.selected).forEach(item => {
          scope.remove(item);
        });
      };
    }
  };
}
