(function () {
    global.dashModule
        .controller('uploadProductDocumentCtrl', ['$scope', '$', '$http', '$translate', 'utilsService', 'Upload', uploadProductDocumentCtrl])
        .directive('uploadProductDocument', [uploadProductDocumentDirective]);

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

    function uploadProductDocumentCtrl($scope, $, $http, $translate, utilsService, Upload) {
        $scope.uploadFile = uploadFile;
        $scope.getDocumentTypes = getDocumentTypes;
        $scope.selectFileType = selectFileType;
        $scope.visibleToCustomer = '1';
        $scope.selectedFileType = {};
        const idSupplierProduct = $scope.$parent.data.idProduct;

        function getDocumentTypes() {
            $http({
                url: 'documents/api/getDocumentTypes',
                method: 'POST',
                data: $.param({
                    withoutTemplates: true
                })
            }).then(setDocumentTypes, utilsService.onHttpError);
        }

        function setDocumentTypes(response){
            if(response.data && response.data.length){
                $scope.documentTypes = response.data.filter((documentType) => {
                    return documentType.isSpecialType !== 1;
                });
            }
        }

        function selectFileType(docType){
            $scope.selectedFileType = docType;
        }

        function uploadFile(file) {
            Upload.upload({
                url: 'suppliers/api/uploadProductDocument',
                method: 'POST',
                file: file,
                data: {
                    idSupplierProduct,
                    idDocumentType: $scope.selectedFileType.idDocumentType || 0,
                    visibleToCustomer: $scope.visibleToCustomer,
                    documentName: $scope.documentName
                }
            }).then(displayMessage, utilsService.onHttpError);
        }

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