/**
 * Query Block frontend features:
 * Responsive columns, sorting & filtering.
 * 
 * @since 1.5.0
 */
document.addEventListener("DOMContentLoaded", function() {

	var mediaQueries = { trigger: {} };
	function initQueries() {
		var queryBlocks = document.querySelectorAll('.wp-block-query .greyd-posts-slider[live-query="true"]');
		if (queryBlocks.length == 0) return;
		
		// get wp rest api url from localized script
		const wp_rest_url = WP_REST_API.root + WP_REST_API.paths.livequery;

		// initial breakpoint to trigger events on load
		let initialBreakpoint = null;

		// live query change function
		const triggerChange = function(obj, perPage = false) {
			// console.log(obj);

			// get block data
			var block = JSON.parse(obj.wrap.getAttribute("data-block-data"));

			// modify sorting attributes
			if (obj.sorting.length > 0) {
				var sort = obj.sorting[0].selectedOptions[0].value.split(' ');
				block.attrs.query.query.orderby = sort[0];
				block.attrs.query.query.order = sort[1].toLowerCase();
			}

			// modify filter (taxQuery) attributes
			if (obj.filter.length > 0) {
				var filter = obj.filter[0].value.split(',');
				var taxQuery = {};
				filter.forEach(function(f) {
					if (f != "") {
						var [ slug, id ] = f.split('|');
						if (typeof taxQuery[slug] === 'undefined') taxQuery[slug] = [];
						taxQuery[slug].push(parseInt(id));
					}
				})
				block.attrs.query.query.taxQuery = taxQuery;
				block.attrs.query.query.taxQueryRelationship = 'OR';
			}

			// modify perPage attribute
			if (obj.perPage.length > 0) {
				var ppp = obj.perPage[0].selectedOptions[0].value;
				block.attrs.query.query.perPage = ppp;
			}
			else if (perPage) {
				block.attrs.query.query.perPage = perPage;
			}
			// console.log(block.attrs.query.query);

			// abort old request
			// happens when two ore more breakpoints are crossed
			if (obj.request) {
				// console.info("abort "+obj.wrap.id);
				obj.request.abort("abort");
			}

			// /* get all background ids*/
			// let bgs = obj?.wrap.querySelectorAll('[id^=bg_]');
			// let bgIds = [];
			
			// for (let i = 0; i < bgs.length; i++) {
			// 	bgIds.push(bgs[i].id);
			// }

			// /* get all list ids*/
			// let lists = obj?.wrap.querySelectorAll('[id^=list_]');
			// let listIds = [];
			
			// for (let i = 0; i < lists.length; i++) {
			// 	listIds.push(lists[i].id);
			// }

			// make post data
			var postdata = { block: JSON.stringify(block) };
			if ( block.attrs.query.advancedFilter ) {
				// send global post id for advanced filter
				postdata.postId = obj.wrap.getAttribute("data-post-id") ?? -1
			}
			var query_vars = JSON.parse(obj.wrap.getAttribute("data-wp-query"));
			if ( query_vars ) {
				// send wp_query for conditional content
				postdata.wp_query = obj.wrap.getAttribute("data-wp-query");
			}

			// send language
			postdata.lang = WP_REST_API.lang;

			// send request
			obj.request = jQuery.ajax({
				type: "POST",
				contentType: "application/json; charset=utf-8",
				url: wp_rest_url,
				data: JSON.stringify( postdata ),
			})
			.always( function() {
				obj.spinner[0].style.display = 'none';
				obj.request = false;
			} )
			.done( function onSuccess( response ) {
				// console.log(response);
	
				// /* replace the wrong background ids*/
				// let wrongBackgroundIds = response.block_content.match(/(id=("|')bg_.*?)(?="|')/g);
				// if ( wrongBackgroundIds && wrongBackgroundIds.length > 0 ) {
				// 	for (var i = 0; i < bgIds.length; i++) {
				// 		if ( typeof wrongBackgroundIds[i] !== 'undefined' ) {
				// 			wrongBackgroundIds[i] = wrongBackgroundIds[i].replace(/(id=("|'))/, '');
				// 			response.block_content = response.block_content.replace( wrongBackgroundIds[i],  bgIds[i]);
				// 		}
				// 	}
				// }
			
				// /* replace the wrong list ids*/
				// let wrongListIds = response.block_content.match(/(id=("|')list_.*?)(?="|')/g);
				// for (var i = 0; i < listIds.length; i++) {
				// 	wrongListIds[i] = wrongListIds[i].replace(/(id=("|'))/, '');
				// 	response.block_content = response.block_content.replace( wrongListIds[i],  listIds[i]);
				// }
				
				obj.spinner[0].remove();
				obj.wrap.outerHTML = response.block_content;
				
				// init custom JS events
				// deprecated classic greyd features
				if ( typeof custom_inputs !== 'undefined' && typeof custom_inputs.init === 'function' ) {
					custom_inputs.init();
				}
				if ( typeof posts !== 'undefined' && typeof posts.init === 'function' ) {
					posts.init();
				}
				if ( typeof sorting !== 'undefined' && typeof sorting.init === 'function' ) {
					sorting.init();
				}
				if ( typeof tablesort !== 'undefined' && typeof tablesort.init === 'function' ) {
					tablesort.init();
				}
				// input (multiselects, selects, checkboxes, radios) features FSE
				if ( typeof greyd.input !== 'undefined' && typeof greyd.input.init === 'function' ) {
					greyd.input.init();
				}
				// query (post-slider) features FSE
				if ( typeof greyd.query !== 'undefined' && typeof greyd.query.init === 'function' ) {
					greyd.query.init();
				}
				if ( typeof greyd.trigger !== 'undefined' && typeof greyd.trigger.init === 'function' ) {
					greyd.trigger.init();
				}
				if ( typeof greyd.lazyload !== 'undefined' && typeof greyd.lazyload.init === 'function' ) {
					greyd.lazyload.init();
				}
				if ( typeof greyd.scrollObserver !== 'undefined' && typeof greyd.scrollObserver.init === 'function' ) {
					greyd.scrollObserver.init();
				}
				// re-init popovers
				if ( typeof greyd.popover !== 'undefined' && typeof greyd.popover.initPopover === 'function' ) {
					greyd.popover.initPopover();
				}
			
				// re-init this
				initQueries();
			} )
			.fail( function onError( XHR, textStatus ) {
				if (textStatus == "abort") {
					// console.info("old call aborted");
				}
				else {
					console.error("Failed to fetch Data: " + textStatus);
					console.log(XHR);
				}
			} );

			// mod html
			// show spinner
			// obj.spinner[0].style = '';
			obj.spinner[0].style.display = 'block';
			obj.spinner[0].style.position = 'absolute';
			obj.spinner[0].style.top = 0;
			// hide greyd-posts-slider
			// obj.wrap.style.display = 'none';
			obj.wrap.style.opacity = 0;

		};

		// media query trigger function
		const triggerMatch = function(event) {
			// console.log(event);
			if (event.matches) {
				// console.log(event);
				var bp = event.target.bp;
				// console.log('Switch to '+bp+' screen.');
				Object.keys(mediaQueries.trigger).forEach(function(key, index) {
					// console.log(key);
					// console.log(mediaQueries.trigger[key]);
					var items = mediaQueries.trigger[key].items;
					if (typeof items[bp] !== 'undefined') {
						// console.info('Switch '+key+' to '+items[bp]+' items per page.');
						triggerChange(mediaQueries.trigger[key].obj, items[bp]);
					}
				});
			} 
		};

		queryBlocks.forEach(function(wrapper, key) {
			// console.log(wrapper);
			let obj = {
				wrap: wrapper,
				sorting: wrapper.querySelectorAll('.sorting select'),
				perPage: wrapper.parentElement.querySelectorAll('.perPage select'),
				filter: wrapper.parentElement.querySelectorAll('.filter input'),
				spinner: wrapper.parentElement.querySelectorAll('.loading_spinner_wrapper'),
				request: false
			};
			// console.log(obj);

			/**
			 * Add select and multiselect events
			 * need to use jQuery as eventlistener
			 * because multiselect trigger is fired with jQuery
			 */
			jQuery([...obj.filter, ...obj.perPage]).off('change').on('change', function(event) {
				triggerChange(obj);
			});

			/**
			 * Add media query events
			 */
			let perPage = obj.wrap.getAttribute("data-perPage");
			if ( perPage ) {
				
				// get perPage data
				perPage = JSON.parse(perPage);
				// console.log(perPage);
				const bps = [ 'sm', 'md', 'lg', 'xl' ];
				const breakpoints = perPage['breakpoints'];
				const current = perPage['current'];
				let items = {};
				if (typeof perPage['items']['xl'] !== 'undefined')
					items = { 'sm': perPage['items']['xl'], 'md': perPage['items']['xl'], 'lg': perPage['items']['xl'], 'xl': perPage['items']['xl'] };
				if (typeof perPage['items']['lg'] !== 'undefined')
					items = { ...items, 'sm': perPage['items']['lg'], 'md': perPage['items']['lg'], 'lg': perPage['items']['lg'] };
				if (typeof perPage['items']['md'] !== 'undefined')
					items = { ...items, 'sm': perPage['items']['md'], 'md': perPage['items']['md'] };
				if (typeof perPage['items']['sm'] !== 'undefined')
					items = { ...items, 'sm': perPage['items']['sm'] };
				// console.log(items);

				// add to trigger list
				mediaQueries.trigger[obj.wrap.id] = { obj: obj, current: current, items: items };

				/**
				 * make media query conditions once on init of first query
				 */
				bps.forEach(function(bp, index) {
					if (typeof mediaQueries[bp] === 'undefined') {
						const breakpoint = breakpoints[bp];
						const conditions = [];
						if (index == 0) conditions.push('(max-width: '+breakpoint+'px)');
						else {
							var previous = breakpoints[bps[index-1]];
							if (index < 3) {
								conditions.push('(min-width: '+previous+'px)');
								conditions.push('(max-width: '+breakpoint+'px)');
							}
							else conditions.push('(min-width: '+previous+'px)');
						}
						// console.log(conditions);

						// match media change event
						mediaQueries[bp] = {};
						mediaQueries[bp].event = window.matchMedia(conditions.join(' and '));
						mediaQueries[bp].event.onchange = triggerMatch;
						mediaQueries[bp].event.bp = bp;
						// console.log(mediaQueries[bp]);
						if (mediaQueries[bp].event.matches && bp != 'xl') {
							// save breakpoint for initial trigger
							initialBreakpoint = bp;
						} 
					}
				});
			}
		});


		// initial trigger
		if ( initialBreakpoint ) {
			triggerMatch({ matches: true, target: { bp: initialBreakpoint } });
		}

		// console.log("query scripts loaded.");
	}
	initQueries();

});