(function () {
    global.dashModule
        .controller('setInterestRateCtrl', ['$scope', '$http', '$', '$translate', 'utilsService', setInterestRateController])
        .directive('setInterestRate', [setInterestRateDirective]);

    function setInterestRateDirective() {
        return {
            restrict: 'E',
            templateUrl: 'financing/html/setInterestRateTemplate'
        };
    }

    function setInterestRateController($scope, $http, $, $translate, utilsService) {
        $scope.getInterestRate = getInterestRate;
        $scope.interestRate = 0;
        $scope.saveInterestRate = saveInterestRate;

        function getInterestRate(){
            $http({
                method: 'POST',
                url: 'financing/api/getInterestRate'
            }).then(setInterestRate, utilsService.onHttpError);
        }

        function setInterestRate(response){
            if(response.data && response.data.interestRate){
                $scope.interestRate = response.data.interestRate;
            }
        }

        function saveInterestRate(){
            const params = $.param({
                interestRate: $scope.interestRate
            });

            $http({
                method: 'POST',
                url: 'financing/api/saveInterestRate',
                data: params
            }).then(showUpdateDefaultMessage, utilsService.onHttpError);
        }

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