(function () {
    global.dashModule
        .directive('copyProcesses', copyProcessesDirective)
        .controller('copyProcessesCtrl', ['$scope', '$http', '$', '$timeout', '$translate', 'utilsService', copyProcessesCtrl]);

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

    function copyProcessesCtrl($scope, $http, $, $timeout, $translate, utilsService) {
        $scope.initPeocessCopy = initPeocessCopy;
        $scope.getSteps = getSteps;
        $scope.resetProcessSelection = resetProcessSelection;

        function initPeocessCopy(){
            getProcessNames();
        }

        function getProcessNames() {
            $http({
                url: 'processes/api/getProcessNames'
            }).then(setProcessNames, utilsService.onHttpError);
        }

        function setProcessNames(response) {
            $scope.processes = response.data || [];
        }

        function getSteps() {
            $scope.processSteps = [];
            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 || {};
                $scope.processSteps = response.data.processSteps|| [];
            }
        }

        function resetProcessSelection() {
            $scope.idSelectedProccess = null;
            $scope.processSteps = [];
        }
    }
})();
