(function () {
    global.dashModule
        .controller('addSupplierBidCtrl', ['$scope', '$http', '$', '$translate', 'utilsService', addSupplierBidCtrl]);

    function addSupplierBidCtrl($scope, $http, $, $translate, utilsService) {
        $scope.getSuppliers = getSuppliers();
        $scope.saveSupplierBid = saveSupplierBid;
        $scope.onSupplierSelect = onSupplierSelect;
        $scope.onProductSelect = onProductSelect;
        $scope.supplierBid = {};

        function getSuppliers(){
            $http({
                method: 'GET',
                url: 'bids/api/getSuppliers'
            }).then(setSuplliers, utilsService.onHttpError);
        }

        function setSuplliers(response){
            if (response.data) {
                $scope.suppliers = response.data;
            }
        }

        function getProducts(idSupplier){
            $http({
                method: 'POST',
                url: 'bids/api/getProducts',
                data: $.param({
                    idSupplier
                })
            }).then(setProducts, utilsService.onHttpError);
        }

        function setProducts(response){
            if (response.data) {
                $scope.products = response.data;
            }
        }

        function onSupplierSelect(){
            $scope.selectedProduct = null;
            $scope.supplierBid.idSupplier = $scope.selectedSupplier.idSupplier;

            if ($scope.selectedSupplier.idSupplier) {
                getProducts($scope.selectedSupplier.idSupplier);
            }
        }

        function onProductSelect(){
            $scope.supplierBid.idProduct = $scope.selectedProduct ? $scope.selectedProduct.idProduct : 0;
        }

        function saveSupplierBid(){
            $http({
                method: 'POST',
                url: 'bids/api/addSupplierBid',
                data: $.param({
                    supplierBid: JSON.stringify($scope.supplierBid)
                })
            }).then(displayMessage, utilsService.onHttpError);
        }

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