global.dashModule
    .directive('createPackages', createPackagesDirective)
    .controller('createPackagesCtrl', ['$scope', '$http', '$', '$translate', 'utilsService', 'packagesUtilsService', createPackagesCtrl]);

function createPackagesDirective() {
    return {
        restrict: 'E',
        templateUrl: 'packages/html/createPackagesTemplate'
    };
}

function createPackagesCtrl($scope, $http, $, $translate, utilsService, packagesUtilsService) {
    $scope.initializeCreatePackages = initializeCreatePackages;
    $scope.isCountrySelected = isCountrySelected;
    $scope.getCountryTranslationKey = getCountryTranslationKey;
    $scope.setCountrySelectedName = setCountrySelectedName;

    function initializeCreatePackages() {
        const params = {getArray: true};
        httpCall('countries/api/getAllCountries', getCountries, params);
    }

    function httpCall(httpUrl, successCallback, params) {
        const urlParams = params ? $.param(params) : {};
        $http({
            method: 'POST',
            url: httpUrl,
            data: urlParams
        }).then(successCallback, utilsService.onHttpError);
    }

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

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

    function getCountryTranslationKey() {
        const countrySelected = packagesUtilsService.getCountryAndPackageSelected().countrySelected || {};
        const countryName = countrySelected.name || '';
        $scope.translationData = {
            country: countryName
        };
        return !countryName ? 'SELECT_COUNTRY' : 'SELECTED_COUNTRY';
    }

    function setCountrySelectedName() {
        packagesUtilsService.setCountryAndPackageSelected(searchPackageNameSelected(), $scope.selectedCountryId);
    }

    function searchPackageNameSelected() {
        const countrySelected = $scope.countries.find(info => {
            return info.id === $scope.selectedCountryId;
        });

        return countrySelected ? countrySelected.name : '';
    }
}
