(function () {
    global.dashModule
        .controller('showProductDocumentsCtrl', ['$scope', '$http', '$', '$translate', 'utilsService', showProductDocumentsCtrl])
        .directive('showProductDocuments', [showProductDocumentsDirective]);

    function showProductDocumentsDirective() {
        return {
            restrict: 'E',
            templateUrl: 'suppliers/html/showProductDocumentsTemplate'
        };
    }

    function showProductDocumentsCtrl($scope, $http, $, $translate, utilsService) {
        $scope.data = $scope.data || {};
        $scope.removeProductDocument = removeProductDocument;

        function removeProductDocument(idDocument){
            const params = $.param({
                idDocument
            });
            const url = 'suppliers/api/removeProductDocument';

            $http({
                method: 'POST',
                url: url,
                data: params
            }).then(showUpdateMessage, utilsService.onHttpError);
        }

        function showUpdateMessage(response) {
            if (typeof response.data.messages !== 'undefined') {
                response.data.messages.forEach((messageObj) => {
                    let translatedMessage = $translate.instant('suppliers.messages.' + messageObj.message);
                    utilsService.displayMessage(messageObj.code, translatedMessage);
                    if (typeof $scope.onUpdated !== 'undefined' && messageObj.code === 'success') {
                        $scope.onUpdated();
                    }
                });
            }
        }
    }
})();
