/**
 * @description Function to handle the search request from Bing Custom Search API
 * 
 * @param {string} searchword - The search term entered by the user
 * @param {string} customconfig - The ID of the custom search engine
 * @param {string} subscriptionKey - The subscription key for the Bing Custom Search API
 * @return {void} - An array of search results or null if the search fails
 */
const handleSearchRequest = (searchword, customconfig, subscriptionKey) => {
	if(!searchword || !customconfig || !subscriptionKey) return

	const params = {
		q: searchword,
		customconfig,
		count: 50,
		offset: 0,
	};

	$.ajax({
		url: "https://api.bing.microsoft.com/v7.0/custom/search?" + $.param(params),
		beforeSend: function (xhrObj) {
			// Request headers
			xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
		},
		type: "GET",
		data: { format: "json" },
	})
	.done((data) => {
		$("ul#resultList li h4:contains('No results')").parent().remove();
		const resMainline = data.rankingResponse.mainline;
		const webPages = resMainline ? data.webPages.value.filter((item) => !item.url.includes("store/order")) : null;
      const prorityURLs = ['/products/', '/oscilloscope/', '/vector-network-analyzer/', '/agile-synthesizer/', '/pulse-generator/', '/accessories/', '/data-logger/'];
      // Loop through the webPages array and sort the results based on the priorityURLs. If the URL contains any of the priorityURLs, it will be moved to the top of the list and the rest will be sorted based on the relevance.
      const formattedResults = webPages?.sort((a, b) => {
         if (prorityURLs.some((url) => a.url.includes(url))) {
            return -1;
         } else if (prorityURLs.some((url) => b.url.includes(url))) {
            return 1;
         } else {
            return 0;
         }
      });

		if (!resMainline || !webPages?.length) {
			if(customconfig !== "c2556947-7e35-4d8c-9667-5e094fbf92c8"){
				handleSearchRequest(searchword, "c2556947-7e35-4d8c-9667-5e094fbf92c8", "adbeb6e9eaa44fa98eca380d1dc981ee");
			}
			$("ul#resultList").append("<li><h4>No results</h4></li>");
			return
		}

		$("ul#resultList").append("<li><h2>Search results for " + searchword + "</h2></li>");

		$.each(formattedResults, function (i, v) {
			$("ul#resultList").append(
				"<li><h4><a href='" +
					formattedResults[i].url +
					"'>" +
					formattedResults[i].name +
					"</a></h4><h6 class='display-url'>" +
					formattedResults[i].displayUrl +
					"</h6><div>" +
					formattedResults[i].snippet +
					"</div></li>"
			);
		});
	})
	.fail(() => {
		alert("An error occurred while searching");
		return
	});
}

$("#searchText").keyup(function (event) {
	// open fancybox pressing "Enter"
	if (event.keyCode === 13) {
		$.fancybox.open({
			openEffect: "fade",
			openSpeed: 150,
			closeEffect: "fade",
			closeSpeed: 150,
			maxWidth: 800,
			maxHeight: 600,
			fitToView: false,
			width: "70%",
			height: "70%",
			autoSize: false,
			scrolling: "auto",
			autoCenter: "false",
			topRatio: 0,
			centerOnScroll: "false",
			src: "#resultList",
			helpers: {
				overlay: {
					css: {
						background: "rgba(87,120,165,0.55)",
					},
				},
			},
		});
		$("ul#resultList").empty();
		var searchword = $("#searchText").val();

		handleSearchRequest(searchword, "114f22d9-b6f3-4c02-b260-1d078c7b41d0", "0791451ec9714ad1b0f34f81f1915e8c");
	}
});

$("#searchTextMobile").keyup(function (event) {
	// open fancybox pressing "Enter"
	if (event.keyCode === 13) {
		$.fancybox.open({
			openEffect: "fade",
			openSpeed: 150,
			closeEffect: "fade",
			closeSpeed: 150,
			maxWidth: 800,
			maxHeight: 600,
			fitToView: false,
			width: "70%",
			height: "70%",
			autoSize: false,
			scrolling: "auto",
			autoCenter: "false",
			topRatio: 0,
			centerOnScroll: "false",
			src: "#resultList",
			helpers: {
				overlay: {
					css: {
						background: "rgba(87,120,165,0.55)",
					},
				},
			},
		});
		$("ul#resultList").empty();
		var searchword = $("#searchTextMobile").val();
		
		handleSearchRequest(searchword, "114f22d9-b6f3-4c02-b260-1d078c7b41d0", "0791451ec9714ad1b0f34f81f1915e8c");
	}
});
