(function() {
    global.dashModule.directive('uploadImageCdn', uploadImageCdnDirective);

    function uploadImageCdnDirective() {
        return {
            restrict: 'EA',
            scope: {
                uploadParams: '@'
            },
            controller: uploadImageCdnCtrl,
            templateUrl: 'packages/html/uploadImageCdnTemplate'
        };
    }

    function uploadImageCdnCtrl($scope, $, $http, $translate, utilsService, Upload) {
        $scope.uploadImage = uploadImage;
        $scope.options = {};
        $scope.parseUploadParams = parseUploadParams;


        function parseUploadParams() {
            $scope.uploadParams = JSON.parse($scope.uploadParams);
            $scope.showUseProfilePictureBox = 'shouldShowBox' in $scope.uploadParams ? $scope.uploadParams.shouldShowBox : true;
        }

        function uploadImage(file) {
            if(typeof $scope.uploadParams === 'string') {
                $scope.uploadParams = JSON.parse($scope.uploadParams);
            }
            $scope.options.idPackage = $scope.uploadParams.idPackage || 0;
            $scope.options.folder = $scope.uploadParams.idCountry || 0;

            Upload.upload({
                url: 'packages/api/uploadNewImage',
                method: 'POST',
                file,
                data: {
                    options: $scope.options
                }
            }).then(getUploadedImageUrl, utilsService.onHttpError);
        }

        function getUploadedImageUrl(response) {
            if (typeof response.data.imageUrl !== 'undefined') {
                $scope.imageUrl = response.data.imageUrl;
            }
            displayUpdateMessage(response);
        }

        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);

                    if(messageObj.code === 'success') {
                        $scope.options = {};
                        utilsService.executeRegisteredFunction('getImagesFromCdn');
                    }
                });
            }
        }
    }
})();
