(function () {
    global.dashModule
        .directive('sortableSteps', ['$timeout', '$', sortableDirective]);

    function sortableDirective($timeout, $) {
        return {
            restrict: 'A',
            scope: {
                processSteps: '=',
                startDragProcess: '=',
                endDragProcess: '='
            },
            link: function ($scope, $element) {
                $timeout(function () {
                    $('.rearrange-steps').sortable({
                        connectWith: 'ul',
                        start: function (event, ui) {
                            var startPos = ui.item.index();
                            ui.item.data('start_pos', startPos);
                            $scope.startDragProcess(event, ui);
                        },
                        update: function (event, ui) {
                            var startPosition = ui.item.data('start_pos');
                            var endPosition = ui.item.index();
                            const movedStep = $scope.processSteps[startPosition];
                            $scope.processSteps.splice(startPosition, 1);
                            $scope.processSteps.splice(endPosition, 0, movedStep);
                            $scope.endDragProcess();
                        },
                        stop: function() {
                            $scope.endDragProcess();
                        }
                    });
                    $('.rearrange-steps').sortable('refreshPositions');
                    $($element).disableSelection();
                });

            }
        };
    }
})();
