(function () {
    global.dashModule
        .controller('orderProjectsEditCtrl', ['$scope', '$http', '$', '$translate', 'utilsService', orderProjectsEditCtrl])
        .directive('orderProjectsEdit', [orderProjectsEditDirective]);

    function orderProjectsEditDirective() {
        return {
            restrict: 'E',
            templateUrl: 'orderProjects/html/orderProjectsEditTemplate'
        };
    }

    function orderProjectsEditCtrl($scope, $http, $, $translate, utilsService) {
        $scope.editOrderProject = editOrderProject;

        function editOrderProject(){
            const params = $.param({
                projectData: JSON.stringify($scope.data)
            });

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

        function showUpdateMessage(response) {
            if (typeof response.data.messages !== 'undefined') {
                response.data.messages.forEach((messageObj) => {
                    const key = messageObj.key ? $translate.instant('orders.tables.headers.' + messageObj.key) : '';
                    let translatedMessage = $translate.instant('orderProjects.messages.' + messageObj.message);
                    translatedMessage = key !== '' ? key + ': ' + translatedMessage : translatedMessage;
                    utilsService.displayMessage(messageObj.code, translatedMessage);
                    if (typeof $scope.onUpdated !== 'undefined' && messageObj.code === 'success') {
                        $scope.onUpdated();
                    }
                });
            }
        }
    }
})();
