(function () {
    global.dashModule
        .directive('addVirtualProducts', addVirtualProductsDirective)
        .controller('addVirtualProductsCtrl', ['$scope', '$', '$http', '$translate', 'utilsService', 'packagesUtilsService', addVirtualProductsCtrl]);

    function addVirtualProductsDirective() {
        return {
            restrict: 'E',
            templateUrl: 'packages/html/addVirtualProductsTemplate'
        };
    }

    function addVirtualProductsCtrl($scope, $, $http, $translate, utilsService, packagesUtilsService) {
        $scope.getProductCategories = getProductCategories;
        $scope.addVirtualProduct = addVirtualProduct;

        function getProductCategories(selectedCategory = '') {
            $scope.selectedCategory = selectedCategory;
            packagesUtilsService.getProductCategories().then(showProductCategories, utilsService.onHttpError);
        }

        function showProductCategories(response) {
            $scope.productCategories = response.data && response.data.length ? response.data : [];
        }

        function addVirtualProduct() {
            const params = $.param({
                productName: $scope.name,
                idCategory: $scope.category && $scope.category.id ? $scope.category.id : 0
            });

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

        function displayMessage(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.name = '';
                        utilsService.executeRegisteredFunction('getVirtualProductsByCategories');
                    }
                });
            }
        }
    }
})();
