(function () {
    global.dashModule
        .directive('linkProcess', linkProcessDirective)
        .controller('linkProcessCtrl', ['$scope', '$http', '$', '$timeout', '$translate', 'utilsService', linkProcessCtrl]);

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

    function linkProcessCtrl($scope, $http, $, $timeout, $translate, utilsService) {
        $scope.packages = {};
        $scope.getPackages = getPackages;
        $scope.isPackageSelected = isPackageSelected;
        $scope.getCountries = getCountries;
        $scope.isCountrySelected = isCountrySelected;
        $scope.getProcesses = getProcesses;
        $scope.processDragStart = processDragStart;
        $scope.processDragStop = processDragStop;
        $scope.prcessDrop = prcessDrop;
        $scope.linkProcesses = linkProcesses;
        $scope.isNewStepFormVisible = isNewStepFormVisible;
        $scope.enableAddNewProcess = enableAddNewProcess;
        $scope.showProcessInfo = showProcessInfo;
        $scope.isVisibleToCustomer = isVisibleToCustomer;
        $scope.addingNewStep = false;
        $scope.processes = [];
        $scope.selectedProcesses = [];
        $scope.selectedSteps = {
            steps: [],
            processName: ''
        };

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

        function processDragStart(event, ui) {
            const containerSelector = $(ui.helper).hasClass('available-process') ? '#available-processes' : '#selected-processes';
            const dropSelector = containerSelector === '#selected-processes' ? '#available-processes' : '#selected-processes';
            $(containerSelector).css({
                height: 'auto',
                overflow: 'visible',
            });

            $(dropSelector).css({
                border: '2px dashed #000',
                background: 'rgba(223, 240, 216, 0.5)'
            });
        }

        function processDragStop(event, ui) {
            const containerSelector = $(ui.helper).hasClass('available-process') ? '#available-processes' : '#selected-processes';
            const dropSelector = containerSelector === '#selected-processes' ? '#available-processes' : '#selected-processes';
            $(containerSelector).css({
                height: '360px',
                'overflow-y': 'scroll',
                'overflow-x': 'hidden',
            });

            $(dropSelector).css({
                border: '2px solid #000',
                background: 'none'
            });
        }

        function prcessDrop(event, ui) {
            const processKey = $(ui.helper).attr('process-key');
            if ($(ui.helper).hasClass('available-process')) {
                $scope.selectedProcesses.push($scope.processes[processKey]);
                $scope.processes.splice(processKey, 1);
                $scope.selectedProcesses.sort(utilsService.sortByAttributeName('processName'));
            } else {
                $scope.processes.push($scope.selectedProcesses[processKey]);
                $scope.selectedProcesses.splice(processKey, 1);
                $scope.processes.sort(utilsService.sortByAttributeName('processName'));
            }
        }

        function linkProcesses() {
            const params = $.param({
                idPackage: $scope.selectedPackageId,
                selectedProcesses: JSON.stringify($scope.selectedProcesses)
            });

            $http({
                method: 'POST',
                url: 'processes/api/linkProcessesToPackage',
                data: params
            }).then(showUpdateMessage, utilsService.onHttpError);
        }

        function showUpdateMessage(response) {
            if (typeof response.data.messages !== 'undefined') {
                response.data.messages.forEach((messageObj) => {
                    let translatedMessage = $translate.instant('processes.messages.' + messageObj.message);
                    utilsService.displayMessage(messageObj.code, translatedMessage);
                });
            }
        }

        function getPackages() {
            const params = $.param({
                idCountry: $scope.selectedCountryId
            });
            $http({
                method: 'POST',
                url: 'processes/api/getPackagesAndProcesses',
                data: params
            }).then(setPackages, utilsService.onHttpError);
        }

        function getProcesses() {
            if ($scope.selectedPackageId) {
                const params = $.param({
                    idPackage: $scope.selectedPackageId
                });
                $http({
                    method: 'POST',
                    url: 'processes/api/getProcesses',
                    data: params
                }).then(setProcesses, utilsService.onHttpError);
            }
        }

        function setProcesses(response) {
            if (typeof response.data.processes !== 'undefined' && typeof response.data.steps !== 'undefined') {
                $scope.steps = response.data.steps;
                $scope.selectedProcesses = [];
                $scope.processes = [];
                response.data.processes.forEach(process => {
                    if (process.isSelected === '1') {
                        $scope.selectedProcesses.push(process);
                    } else {
                        $scope.processes.push(process);
                    }
                });
            }
        }

        function setPackages(response) {
            if (response.data.length) {
                $scope.packages = {};
                response.data.forEach(packageItem => {
                    $scope.packages[packageItem.idPackage] = packageItem.packageName;
                });
            }
        }

        function isPackageSelected() {
            return typeof $scope.selectedPackageId !== 'undefined' && $scope.selectedPackageId !== null;
        }

        function getCountries() {
            $http({
                method: 'GET',
                url: 'countries/api/getAllCountries'
            }).then(setCountries, utilsService.onHttpError);
        }

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

        function isCountrySelected() {
            return typeof $scope.selectedCountryId !== 'undefined' && $scope.selectedCountryId !== 0;
        }

        function isNewStepFormVisible() {
            return $scope.addingNewStep;
        }

        function enableAddNewProcess() {
            $scope.addingNewStep = !$scope.addingNewStep;
        }

        function showProcessInfo(process) {
            $('#info-placeholder').hide();
            $scope.selectedSteps.processName = process.processName;
            $scope.selectedSteps.steps = $scope.steps[process.idProcess];
        }
    }
})();
