( function($) {
	'use strict';

	$(document).ready(function() {
		wcvAdminShopCoupon.init();
	});

	var wcvAdminShopCoupon = {
		init: function() {
			$('.wcv-vendor-select#post_author').on('select2:select', wcvAdminShopCoupon.onSelect);
		},

		onSelect: function (e) {
			var vendor_id = e.params.data.id;

			var couponProductsSelect   = $('select[name="product_ids[]"]');
			var selectedCouponProducts = $('select[name="exclude_product_ids[]"] > option:selected');

			var couponExcludedProductSelect    = $('select[name="exclude_product_ids[]"]');
			var selectedExcludedCouponProducts = $('select[name="exclude_product_ids[]"] > option:selected');

			var data = {
				action: 'wcv_filter_vendor_coupon_products',
				vendor_id: vendor_id,
				coupon_id: wcv_admin_shop_coupon.coupon_id,
				security: wcv_admin_shop_coupon.filter_products_nonce
			};

			$.post(
				wcv_admin_shop_coupon.admin_ajax_url,
				data,
				function (response, textStatus, jqXHR) {

					if ( textStatus != 'success' ) {
						return;
					}

					var couponProducts = response.data.coupon_products;
					var excludedProducts = response.data.excluded_products;

					wcvAdminShopCoupon.processProducts(
						couponProductsSelect,
						selectedCouponProducts,
						couponProducts
					);

					wcvAdminShopCoupon.processProducts(
						couponExcludedProductSelect,
						selectedExcludedCouponProducts,
						excludedProducts
					);
				},
			).error(function(error) {
				wcvAdminShopCoupon.onError(error);
			});
		},

		processProducts: function(productsElement, selectedProducts, products) {
			if ( products.length < 1 ) {
				$(productsElement).html('');
				return;
			}

			if ( selectedProducts.length > 0 ) {
				$.each(selectedProducts, (index, element) => {
					const productId = $(element).val();

					if (! $.inArray( productId, products ) > 0 ) {
						$(productsElement).find(element).remove();
					}
				});
				return;
			}

			$.each(products, (index, product ) => {
				var id = product.id;
				var title = product.title;
				$(productsElement).append( '<option value="' + id + '" selected="selected">' + title + ' (#' + id +')</option>');
			});
		},

		onError: function(error) {
			console.log(error);
		}
	}

})(jQuery);
