(function () {
    global.dashModule
        .directive('editProcesses', editProcessesDirective)
        .controller('editProcessesCtrl', ['$scope', '$http', '$', '$timeout', '$translate', 'utilsService', editProcessesCtrl]);

    function editProcessesDirective() {
        return {
            restrict: 'E',
            templateUrl: 'processes/html/editProcessesTemplate'
        };
    }

    function editProcessesCtrl($scope, $http, $, $timeout, $translate, utilsService) {
        let processStepsHeight;
        let availableStepDragged = {};
        let processStepDragged = {};
        $scope.initPRocessEdit = initPRocessEdit;
        $scope.getSteps = getSteps;
        $scope.isProcessSelected = isProcessSelected;
        $scope.getStepPadding = getStepPadding;
        $scope.startDragFromAvailableSteps = startDragFromAvailableSteps;
        $scope.endDragFromAvailableSteps = endDragFromAvailableSteps;
        $scope.availableStepDropped = availableStepDropped;
        $scope.startDragFromProcessSteps = startDragFromProcessSteps;
        $scope.endDragFromProcessSteps = endDragFromProcessSteps;
        $scope.processStepDropped = processStepDropped;
        $scope.editProcess = editProcess;
        $scope.setProcessAfterEdit = setProcessAfterEdit;
        $scope.resetProducts = resetProducts;
        $scope.isVisibleToCustomer = isVisibleToCustomer;

        function isVisibleToCustomer(stepVisibleInfo) {
            return stepVisibleInfo === '1' ? 'glyphicon-eye-open' : 'glyphicon-eye-close';
        }

        function initPRocessEdit(){
            getProcessNames();
            getCountries();
        }

        function getProcessNames(isAfterEdit = false) {
            $http({
                methos: 'POST',
                url: 'processes/api/getProcessNames'
            }).then((response) => {setProcessNames(response, isAfterEdit);}, utilsService.onHttpError);
        }

        function setProcessNames(response, isAfterEdit) {
            $scope.processes = response.data ? response.data : [];
            if(isAfterEdit){
                setProcessAfterEdit();
            }
        }

        function getCountries() {
            const params = $.param({
                getArray: true
            });
            $http({
                method: 'POST',
                data: params,
                url: 'countries/api/getAllCountries'
            }).then(setCountries, utilsService.onHttpError);
        }

        function setCountries(response){
            if(response.data){
                $scope.countries = response.data;
            }
        }

        function getSteps() {
            const processSelected = $scope.processes.find(processData => {
                return processData.id === $scope.idSelectedProccess.id;
            });
            $scope.processName = processSelected.name;
            $scope.selectedCountry = processSelected.idCountry;
            $http({
                method: 'POST',
                data: $.param({
                    idProcess: $scope.idSelectedProccess.id
                }),
                url: 'processes/api/getStepsForProcessSelected'
            }).then(setSteps, utilsService.onHttpError);
        }

        function setSteps(response) {
            if (response.data) {
                $scope.availableSteps = response.data.steps ? response.data.steps : {};
                $scope.processSteps = response.data.processSteps ? response.data.processSteps : [];
            }

            processStepsHeight = $('#process-steps-list').height();
            $('.available-steps-list').css({
                height: processStepsHeight
            });
        }

        function isProcessSelected() {
            return $scope.idSelectedProccess && $scope.idSelectedProccess.id ? $scope.idSelectedProccess.id : $scope.idSelectedProccess;
        }

        function getStepPadding(position) {
            return (position + 1) * 2;
        }

        function startDragFromAvailableSteps(event, ui, idStepDragged) {
            $('#available-steps-list').css({
                height: '400px',
                overflow: 'visible'
            });

            $('#process-steps-list').addClass('allowed-drop-zone');
            availableStepDragged = {
                idStep: idStepDragged,
                shortDesc: $scope.availableSteps[idStepDragged].shortDesc,
                isVisibleForCustomer: $scope.availableSteps[idStepDragged].isVisibleForCustomer
            };
        }

        function endDragFromAvailableSteps() {
            $('#available-steps-list').css({
                height: processStepsHeight,
                'overflow-y': 'scroll'
            });

            $('#process-steps-list').removeClass('allowed-drop-zone');
        }

        function availableStepDropped(event, ui) {
            let isStepMoved = false;
            if (Object.keys(availableStepDragged).length === 0) {
                processStepDragged = JSON.parse($(ui.helper).attr('step-info'));
                if (typeof processStepDragged === 'object') {
                    isStepMoved = $scope.processSteps.some(processStep => {
                        return processStep.idStep === processStepDragged.idStep;
                    });
                }
            }

            if (!isStepMoved) {
                $scope.processSteps.push(availableStepDragged);
                delete $scope.availableSteps[availableStepDragged.idStep];
                availableStepDragged = {};
            }

            $(ui.helper).css({
                position: 'relative',
                left: 0,
                top: 0
            });
        }

        function startDragFromProcessSteps(event, ui) {
            $('#process-steps-list').css({
                height: '400px',
                overflow: 'visible'
            });

            $('#available-steps-list').addClass('allowed-drop-zone');
            $('#process-steps-list').addClass('allowed-drop-zone');
            processStepDragged = JSON.parse($(ui.helper).attr('step-info'));
        }

        function endDragFromProcessSteps() {
            processStepsHeight = $('#process-steps-list').height();
            $('#process-steps-list').css({
                height: processStepsHeight,
                'overflow-y': 'scroll'
            });

            $('#available-steps-list').removeClass('allowed-drop-zone');
            $('#process-steps-list').removeClass('allowed-drop-zone');
            $timeout(function () {
                $('.rearrange-steps').sortable('refreshPositions');
            });
        }

        function processStepDropped(event, ui) {
            if (typeof processStepDragged.idStep !== 'undefined') {
                $scope.availableSteps[processStepDragged.idStep] = processStepDragged;
                $scope.processSteps = $scope.processSteps.filter(removeDroppedStep);
            }

            processStepDragged = {};

            $(ui.helper).css({
                position: 'relative',
                left: 0,
                top: 0
            });
        }

        function removeDroppedStep(processStep) {
            return processStep.idStep !== processStepDragged.idStep;
        }

        function editProcess() {
            if ($scope.processSteps.length !== 0) {
                $http({
                    method: 'POST',
                    url: 'processes/api/editProcess',
                    data: $.param({
                        idProcess: $scope.idSelectedProccess.id,
                        data: {
                            processName: $scope.processName,
                            idCountry: $scope.selectedCountry,
                            processSteps: $scope.processSteps
                        }
                    })
                }).then(displayEditMessage, utilsService.onHttpError);
            } else {
                const message = $translate.instant('processes.messages.NO_STEPS');
                utilsService.displayMessage('error', message);
            }
        }

        function displayEditMessage(response) {
            if (response.data.hasOwnProperty('messageData') && response.data.messageData.length > 0) {
                response.data.messageData.forEach(messageData => {
                    const message = $translate.instant('processes.messages.' + messageData.message);
                    utilsService.displayMessage(messageData.code, message);

                    if (messageData.code === 'success') {
                        getProcessNames(true);
                    }
                });
            }
        }

        function setProcessAfterEdit(idProcessUpdated = 0) {
            if (idProcessUpdated) {
                $scope.idSelectedProccess = {
                    id: idProcessUpdated
                };
                getSteps();
            }
        }

        function resetProducts() {
            getSteps();
            const message = $translate.instant('processes.messages.RESET_PROCESS');
            utilsService.displayMessage('success', message);
        }
    }
})();
