jQuery(function ($) {

	console.log('Lite Scripts Loaded');

	/**
	 * Added Image Uploader Filed
	 */
	$('body').on('click', '.gs_upload_image_button', function (event) {
		
		event.preventDefault();

		const button = $(this);
		const imageId = button.prev().val();

		const customUploader = wp.media({
			title: 'Insert image', // modal window title
			library: {
				// uploadedTo : wp.media.view.settings.post.id, // attach to the current post?
				type: 'image'
			},
			button: {
				text: 'Use this image' // button label text
			},
			multiple: false
		}).on('select', function () { // it also has "open" and "close" events
			const attachment = customUploader.state().get('selection').first().toJSON();
			button.closest('.gs-meta-image-wrapper').find('.image-preview img').attr('src', attachment.url); // add image instead of "Upload Image"
			button.prev().val(attachment.id); // Populate the hidden field with image ID
			button.next().show();
		})

		// already selected images
		customUploader.on('open', function () {

			if (imageId) {
				const selection = customUploader.state().get('selection')
				attachment = wp.media.attachment(imageId);
				attachment.fetch();
				selection.add(attachment ? [attachment] : []);
			}

		})

		customUploader.open()

	});

	// on remove button click
	$('body').on('click', '.gs_remove_image_button', function (event) {
		event.preventDefault();
		const button = $(this);
		button.hide().prev().prev().val(''); // emptying the hidden field
		let img = button.closest('.gs-meta-image-wrapper').find('.image-preview img');
		img.attr('src', img.data('placeholder')); // add image instead of "Upload Image"
	});

	$( '.gs-color-picker' ).wpColorPicker();

	function match_condition( condition ) {
		
		let condition_key = Object.keys( condition )[0];
		let condition_data = condition[condition_key];

		let $condition_field = $(condition_key, '#addtag, #edittag');

		if ( ! $condition_field.length ) return false;

		if ( condition_data.type == "equal" ) {
			return $condition_field.val() == condition_data.value
		}

		return false;
	}

	function single_field_condition( $field ) {

		var conditions = $field.data('gs-dependency');
		var condition = conditions.every( function( _condition ) {
			return match_condition( _condition );
		});

		condition ? $field.show() : $field.hide();
	}

	$('[data-gs-dependency]').each(function() {
		single_field_condition( $(this) );
	});

	$(document).on('change', function(){
		$('[data-gs-dependency]').each(function() {
			single_field_condition( $(this) );
		});
	});

	/**
	 * Added ajax call to save single product swatches settings
	 */
    $( '.gs_swatches_attributes' ).on( 'click', function(e) {

		e.preventDefault();

		show_loader();

		let input_data = $('.gs-product-swatches-wrapper :input').serializeArray();

		jQuery.ajax({
			url: _single_prod_settings.ajax_url,
			type: 'POST',
			cache: false,
			data: {
				action: 'gs_swatches_ajax_handler',
				route: 'prod_swatches_settings',
				settings: input_data,
				prod_id: _single_prod_settings.product_id,
				_wpnonce: _single_prod_settings.nonce
			}
		}).always(()=>{
			hide_loader();
		});
    } );

	/**
	 * Added ajax call to reset single product swatches settings
	 */
	$( '.gs_woo_variation_swatches_reset_product_attributes' ).on( 'click', function(e) {

		e.preventDefault();	

		show_loader();

		jQuery.ajax({
			url: _single_prod_settings.ajax_url,
			type: 'POST',
			cache: false,
			data: {
				route: 'prod_swatches_reset_settings',
				action: 'gs_swatches_ajax_handler',
				prod_id: _single_prod_settings.product_id,
				_wpnonce: _single_prod_settings.nonce
			}
		}).then( (data) => {

			for ( let key in data.data ) {
				let $input = jQuery( '*[name="'+key+'"]' );

				if ( $input.prop("tagName") =='SELECT' ) {
					$input.val( data.data[key] ).trigger('change');
				}
			}

		}).fail(() => {
			console.log('No data found');
			
		}).always(()=>{
			hide_loader();
		});

	})

	function show_loader() {
		$('#gs-variation-swatches .GSblockOverlay').fadeIn(200);
	}

	function hide_loader() {
		setTimeout(function() {
			$('#gs-variation-swatches .GSblockOverlay').fadeOut(200);
		}, 500);
	}
})
