(function () {
    global.dashModule
        .controller('documentsViewCtrl', ['$scope', '$http', '$', '$translate', 'utilsService', documentsViewController])
        .directive('documentsView', [documentsViewDirective]);

    function documentsViewDirective() {
        return {
            restrict: 'E',
            templateUrl: 'documents/html/documentsViewTemplate'
        };
    }

    function documentsViewController($scope, $http, $, $translate, utilsService) {
        $scope.getDocuments = getDocuments;
        $scope.showHideRemoveDialog = showHideRemoveDialog;
        $scope.removeDocument = removeDocument;
        $scope.documents = [];
        $scope.isRemoveDialogVisible = false;

        function getDocuments() {
            $http({
                method: 'POST',
                url: 'documents/api/getDocuments',
                data: $.param({
                    idDocument: global.getParameterByName('idDocument') || 0,
                    idPackage: global.getParameterByName('idPackage') || 0
                })
            }).then(setDocuments, utilsService.onHttpError);
        }

        function setDocuments(response) {
            if (response.data) {
                $scope.documents = response.data;
            }
        }

        function showHideRemoveDialog(document) {
            if(document){
                $scope.selectedDocument = document;
            }
            $scope.$evalAsync(() => {
                $scope.isRemoveDialogVisible = !$scope.isRemoveDialogVisible;
            });
        }

        function removeDocument(document) {
            const params = $.param({
                idDocument: document.idDocument
            });

            $http({
                method: 'POST',
                url: 'documents/api/removeDocument',
                data: params
            }).then(displayMessage, utilsService.onHttpError);
        }

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