(function () {
    global.dashModule
        .directive('viewPackageProcesses', viewPackageProcessesDirective)
        .controller('viewPackageProcessesController', ['$scope', '$http', '$translate', '$', 'utilsService', viewPackageProcessesCtrl]);

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

    function viewPackageProcessesCtrl($scope, $http, $translate, $, utilsService) {
        $scope.getAvailableProcesses = getAvailableProcesses;
        $scope.listAvailableProcesses = listAvailableProcesses;
        $scope.searchProcess = searchProcess;
        $scope.isVisibleForCustomer = isVisibleForCustomer;
        $scope.countries = [];

        function getAvailableProcesses() {
            $http({
                method: 'GET',
                url: 'processes/api/getProcessInfo'
            }).then(setProcessData, utilsService.onHttpError);
        }

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

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

        function listAvailableProcesses() {
            $scope.searchProcessValue = '';
            getAvailableProcesses();
            utilsService.displayMessage('success', $translate.instant('processes.messages.LIST_ALL_PROCESSES'));
        }

        function searchProcess() {
            const params = $.param({
                name: $scope.searchProcessValue
            });

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

        function getSearchedProcess(response) {
            if (response.data.messageData) {
                let translationDataMessages = '';
                if (response.data.messageData.status === 'success') {
                    let processesFound = 0;
                    $.each(response.data.data, (key, country) => {
                        processesFound += Object.keys(country.processes).length;
                    });
                    translationDataMessages = {
                        processesFound
                    };
                    $scope.countries = response.data.data;
                } else {
                    $scope.countries = [];
                }

                const message = $translate.instant('processes.messages.' + response.data.messageData.message, translationDataMessages);
                utilsService.displayMessage(response.data.messageData.status, message);
            } else {
                utilsService.displayMessage('error', $translate.instant('processes.messages.SERVER_ERROR'));
            }
        }
    }
})();
