(function() {
    global.dashModule.directive('displayCdnImages', displayCdnImagesDirective);

    function displayCdnImagesDirective() {
        return {
            restrict: 'E',
            scope: {
                imageParams: '@'
            },
            controller: displayCdnImagesCtrl,
            templateUrl: 'packages/html/displayCdnImagesTemplate'
        };
    }

    function displayCdnImagesCtrl($scope, $, $http, $translate, utilsService) {
        $scope.getImagesFromCdn = getImagesFromCdn;
        $scope.images = [];

        utilsService.registerFunction('getImagesFromCdn', getImagesFromCdn);
        utilsService.registerFunction('saveCoverImage', saveCoverImage);

        function getImagesFromCdn() {
            $scope.imageParams = typeof $scope.imageParams === 'string' && JSON.parse($scope.imageParams);
            const params = $.param({
                idCountry: $scope.imageParams.idCountry || 0,
                idPackage: $scope.imageParams.idPackage || 0
            });

            $http({
                method: 'POST',
                url: 'packages/api/getImagesFromCdn',
                data: params
            }).then(setImagesPerCountry, utilsService.onHttpError);
        }

        function setImagesPerCountry(response) {
            if(response.data) {
                $scope.images = response.data.resources || [];

                const coverPhoto = $scope.images.find(imageDetails => {
                    return imageDetails.useAsMarketPicture === true;
                });

                $scope.profilePicture = coverPhoto || [];
            }
        }

        function saveCoverImage(imageParams) {
            const coverPhotoDetails = $scope.images.find(imageDetails => {
                return imageDetails.secure_url === $scope.profilePicture.secure_url;
            });

            const params = $.param({
                idPackage: imageParams.idPackage || 0,
                publicId: coverPhotoDetails && coverPhotoDetails.public_id ? coverPhotoDetails.public_id : null
            });

            $http({
                method: 'POST',
                url: 'packages/api/saveCoverPhotoForPackage',
                data: params
            }).then(displayUpdateMessage, utilsService.onHttpError);
        }

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