define([
	'jquery', 
	'Amasty_CheckoutCore/js/action/update-item', 
	'MNM_Spitzner/js/action/update-item-silent',
    'Magento_Checkout/js/model/totals'], function($, updateItem, updateItemSilent, totals) {
	var mixin = {
		itemsData: [],

		updateItemsQty: function() 
		{
			if(!totals.isLoading())
			{
				var forms = $('[data-role="product-attributes"]');
	            var valid = true;
	            var self = this;
	            
	            forms.each(function() {
	        	   	valid = valid && $(this).validation().valid();
	        	});
	            
	            if(valid)
	        	{
	            	totals.isLoading(true);
	            	this.itemsData = [];
            	
	            	forms.each(function() {
	            		var $elem = $(this);
	            		var data = 'qty=' + $elem.find('input[name="qty"]').val();
	            		self.itemsData.push([$elem.data('item-id'), data]);
	            	});
	            	
	            	this.updateNext();
	        	}
        	}
		},
		
		updateNext: function() 
		{
			let itemData = this.itemsData.pop();
			
			if(this.itemsData.length > 0)
			{
				updateItemSilent(itemData[0], itemData[1])
					.done(this.updateNext.bind(this))
					.fail(this.updateNext.bind(this));
			}
			else
			{
				totals.isLoading(false);
				updateItem(itemData[0], itemData[1]);
			}
		}
	};

	return function(target) {
		return target.extend(mixin);
	}
});