/**
 * Autofill search frontend script.
 *
 * @since 1.2.2 (moved from theme/default.js)
 */

(function() {

	jQuery(function() {

		if (typeof $ === 'undefined') $ = jQuery;

		greyd.autosearch.init();

		console.log('Auto search Scripts: loaded');
	} );

} )(jQuery);

greyd.autosearch = new function() {

	this.init = function() {

		// don't execute if deprecated version still loads
		if ( typeof autofill !== 'undefined' && typeof autofill.init === 'function') {
			return false;
		}

		if ( $('.custom-select.autofill').length === 0 ) {
			return false;
		}

		$('.custom-select.autofill').each(function(){
			greyd.autosearch.initAutoSearch( this )
		})
	}

	this.initAutoSearch = function(elem) {

		var wrapper = $(elem);
		var select  = wrapper.find('select');
		var input   = wrapper.closest('[id^="input_"]').find('input[type="search"]');

		wrapper.closest('form').attr('autocomplete', 'off');

		// get the settings
		var settings = {
			showOnClick:        wrapper.data("show-on-click"),
			forwardOnClick:     wrapper.data("forward-on-click"),
			filter:             wrapper.data("filter"),
			resultsPerQuery:    parseInt( wrapper.data("max-results") ),
			orderby:            wrapper.data("orderby"),
			order:              wrapper.data("order"),
			failed:             wrapper.data("noresult-text"),
			loading:            wrapper.data("loading-text")
		};

		// get wp rest api url and replace wp-json with ?rest_route= for compatibility with ugly permalinks
		var wpRestUrl = document.querySelector('link[rel="https://api.w.org/"]').href.replace("wp-json", "?rest_route=");

		// set params
		var params = {
			order: settings.order,
			orderby: settings.orderby,
			autosearch: 'true',
			lang: wp_settings.lang
		};
		if ( settings.filter ) {
			params.subtype = settings.filter;
		}
		if ( settings.resultsPerQuery && Math.floor(settings.resultsPerQuery) ) {
			params.per_page = settings.resultsPerQuery;
		}
		params = Object.keys(params).map(function(key){
			return [key, params[key]].join('=')
		}).join('&');

		// get request URL
		var requestURL = wpRestUrl + 'wp/v2/search/&_fields=title,url,date&' + params + '&search=';

		input.one('focus', function(e) {
			// e.stopPropagation();

			var dropdown = wrapper.find('.select-items');
			dropdown.attr('loading', settings.loading);

			wrapper.find('.select-selected').remove();
			dropdown.children(':empty').remove();

			// append the loader as first child of the dropdown
			// dropdown.append("<div class='loader'>" + settings.loading + "</div>");


			var lastVal = null;

			var xhr = null;
			input.on('keyup click', function(event) {
				event.stopPropagation();

				var value = $(this).val();

				// toggle the dropdown
				if ( ! value.length ) {
					dropdown.addClass('select-hide');
				}
				else if ( settings.showOnClick ) {
					dropdown.removeClass('select-hide');
				}

				const hasChanged = value != lastVal;
				lastVal = value;

				if ( value.length == 0 ) {
					dropdown.empty();
				}
				else if ( hasChanged ) {

					dropdown.children('.failed').remove();
					if ( settings.showOnClick ) {
						dropdown.addClass('loading');
					}

					// abort request if a new request is started
					if (xhr) xhr.abort();

					xhr = $.ajax({
						type: "GET",
						url: requestURL + value
					})
					.done(function(data){

						select.empty();
						dropdown.empty();
						dropdown.removeClass('loading');

						if (data.length) {
							for (var i=0; i < data.length; i++) {
								select.append("<option value='"+data[i].url+"'>"+ data[i].title+"</option>");
								dropdown.append("<div class='animate_fast'>"+ data[i].title+"</div>");
							}
						} else {
							dropdown.append("<div class='animate_fast failed'>" + settings.failed + "</div>");
						}

						// set xhr to null for sending only the last requested input
						xhr = null;
					})
					.fail(function(jqXHR, textStatus){
						if ( textStatus !== "abort" ) {
							console.log("Failed to fetch Data: " + textStatus);

							select.empty();
							dropdown.empty();
							dropdown.removeClass('loading');
							dropdown.append("<div class='animate_fast failed'>" + settings.failed + "</div>");
						}
					});
				}
			});

			dropdown.click(function(e){
				// update the option
				$(select).find('option:contains("' + e.target.innerHTML + '")').attr("selected", true);

				// redirect to the selected post
				if ( settings.forwardOnClick ) {
					window.location.href = $(select).val();
				}
				// default: submit the form with the selected value
				else {
					input.val($(select).find('option:selected').text());
					input.closest("form").submit();
				}
			});
		} );
		return;
	}
}