(function () {
    global.dashModule
        .controller('addBidMarginCtrl', ['$scope', '$http', '$', '$translate', 'utilsService', addBidMarginCtrl])
        .directive('addBidMargin', [addBidMarginDirective]);

    function addBidMarginDirective(){
        return {
            restrict: 'E',
            templateUrl: 'bids/html/addBidMarginTemplate'
        };
    }
    function addBidMarginCtrl($scope, $http, $, $translate, utilsService) {
        $scope.init = init;
        $scope.saveBidMargin = saveBidMargin;
        $scope.bidMargin = {};

        function init(bid){
            $scope.bidMargin.fixedExtra = bid.fixedExtra;
            $scope.bidMargin.recurrentExtra = bid.recurrentExtra;
            $scope.bidMargin.servicesExtra = bid.servicesExtra;
        }

        function saveBidMargin(params){
            $http({
                method: 'POST',
                url: 'bids/api/addBidMargin',
                data: $.param({
                    idBid: params.bid.idBid,
                    bidMargin: JSON.stringify($scope.bidMargin)
                })
            }).then((response)=>{displayMessage(response, params.getBids);} , utilsService.onHttpError);
        }

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