(function () {
    global.dashModule
        .controller('financingController', ['$scope', '$http', '$', '$translate', 'utilsService', financingController])
        .directive('financing', [financingDirective]);

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

    function financingController($scope, $http, $, $translate, utilsService) {
        $scope.getInterestRate = getInterestRate;
        $scope.interestRate = 0;
        $scope.saveInterestRate = saveInterestRate;
        $scope.subModule = 'setInterestRate';
        $scope.setSubModule = setSubModule;
        $scope.isSubmoduleVisible = isSubmoduleVisible;

        function setSubModule($event) {
            $scope.subModule = $event.currentTarget.attributes.subModule.value;
        }

        function isSubmoduleVisible(subModule) {
            return subModule === $scope.subModule;
        }

        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);
                });
            }
        }
    }
})();
