function toggleLoading() {
	document.getElementById('itemList').classList.toggle("hide");
	document.getElementById('loading').classList.toggle("hide");
}

function toggleError() {
	if (document.getElementById("search").value != "") {
		document.getElementById("errorHeader").innerHTML = "Search No Result";
		document.getElementById("errorMessage").innerHTML = "We're sorry. We cannot find any matches for your search term.";
	} else {
		document.getElementById("errorHeader").innerHTML = "No items";
		document.getElementById("errorMessage").innerHTML = "We're sorry. We cannot find any items to be displayed in the catalogue.";
	}
	document.getElementById('loading').classList.toggle("hide");
	document.getElementById('error').classList.toggle("hide");
}

function submitSearch(evt) {
	try {
		// Only Enter key is allowed
		let ASCIICode = (evt.which) ? evt.which : evt.keyCode;
		if (ASCIICode != 13) {
			return true;
		} else {
			updateItemData();
		}
	} catch (error) {
		console.log(error);
	}
}

// Get Methods
// Filter (cat)
async function getCatData() {
	try {
		let catArr = [];
		// Make the params to array
		if (params.has("filterCat")) {
			catArr = params.get("filterCat").split("+");
		}

		let html = '';
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/catData.asp");

		xhr.onload = function () {
			if (this.responseText != "Failed") {
				let categories = JSON.parse(this.responseText);

				categories.forEach(cat => {
					let checked = "";

					if (cat.code == catArr[0]) {
						checked = "checked";
						catArr.shift();
					}

					let htmlSegment = `<label class="list-group-item">
								    	<input class="form-check-input me-1 filterCat" type="checkbox" value="${cat.code}" onchange="updateItemData()" ${checked}>
								    	${cat.desp}
									</label>`;
					html += htmlSegment;
				});
			} else {
				if (html == '') {
					html = `<label class="list-group-item disabled">
								No category available
							</label>`;
				}
			}
			
			document.getElementById('filter-cat-container').innerHTML = html;
		}

		xhr.send();
	} catch (error) {
		console.log(error); 
	}
}

// Filter (group)
async function getGroupData() {
	try {
		let groupArr = [];
		// Make the params to array
		if (params.has("filterGroup")) {
			groupArr = params.get("filterGroup").split("+");
		}

		let html = '';
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/groupData.asp");

		xhr.onload = function () {
			if (this.responseText != "Failed") {
				let groups = JSON.parse(this.responseText);

				groups.forEach(group => {
					let checked = "";

					if (group.rgroup == groupArr[0]) {
						checked = "checked";
						groupArr.shift();
					}

					let htmlSegment = `<label class="list-group-item">
								    	<input class="form-check-input me-1 filterGroup" type="checkbox" value="${group.rgroup}" onchange="updateItemData()" ${checked}>
								    	${group.desp}
									</label>`;
					html += htmlSegment;
				});
			} else {
				if (html == '') {
					html = `<label class="list-group-item disabled">
								No group available
							</label>`;
				}
			}
			document.getElementById('filter-group-container').innerHTML = html;
		}

		xhr.send();
	} catch (error) {
		console.log(error); 
	}
}

// Filter (dept)
async function getDeptData() {
	try {
		let deptArr = [];
		// Make the params to array
		if (params.has("filterDept")) {
			deptArr = params.get("filterDept").split("+");
		}

		let html = '';
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/deptData.asp");

		xhr.onload = function () {
			if (this.responseText != "Failed") {
				let depts = JSON.parse(this.responseText);

				depts.forEach(dept => {
					let checked = "";

					if (dept.code == deptArr[0]) {
						checked = "checked";
						deptArr.shift();
					}

					let htmlSegment = `<label class="list-group-item">
								    	<input class="form-check-input me-1 filterDept" type="checkbox" value="${dept.code}" onchange="updateItemData()" ${checked}>
								    	${dept.desp}
									</label>`;
					html += htmlSegment;
				});
			} else {
				if (html == '') {
					html = `<label class="list-group-item disabled">
								No dept available
							</label>`;
				}
			}
			document.getElementById('filter-dept-container').innerHTML = html;
		}

		xhr.send();
	} catch (error) {
		console.log(error); 
	}
}

function clearFilter() {
	try {
		params.delete("currPage");
		params.delete("sortBy");
		params.delete("filterCat");
		params.delete("filterGroup");
		params.delete("filterDept");

		location.search = "?" + params;
	} catch (error) {
		console.log(error);
	}
}

// Item List
async function getItemData() {
	try {
		toggleLoading();
		let query = location.search;
		if (query == "") { query = "?"; }

		let html = '';
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/itemData.asp" + query + "&query=itemList", true);

		xhr.onload = function () {
			// console.log(this.responseText);
			if (this.responseText != "Failed") {
				let response = JSON.parse(this.responseText);

				if (response.display == "GRID") {
					response.items.forEach(item => {
						let itemDisc = '';
						if (item.showItemDisc && item.discount > 0) {
							itemDisc = `<p class="card-text item-itemDisc"><span class="item-oriPrice">${response.currcode}${priceFormatter.format(item.oriPrice)}</span>&nbsp;&nbsp;<span class="item-discLabel">-${item.discount}%</span></p>`;
						} else {
							itemDisc = `<p></p>`
						}

						let htmlSegment = `<div class="col">
											<a href="itemDetails.asp?itemNo=${item.item_no}" class="card-link">
										    	<div class="card h-100">
										      		<img src="${item.pictpath}" class="card-img-top">
									      			<div class="card-body">
									        			${item.gcatalogue}
									        			<p class="card-text item-itemLabel">${item.icatalogue}</p>
									        			<p class="card-text item-itemNo">${item.item_no} ${item.item_no2}</p>
									        			<p class="card-text item-price"><span class="item-price-label">${response.currcode}</span>${priceFormatter.format(item.price)}</p>
						        						${itemDisc}
									     			</div>
										    	</div>
										  	</a>
										</div>`;
						html += htmlSegment;
					});
				} else {
					response.items.forEach(item => {
						let htmlSegment = `<div class="col">
											<a href="itemDetails.asp?itemNo=${item.item_no}" class="card-link">
										    	<div class="card h-100">
										      		<img src="${item.pictpath}" class="card-img-top">
									      			<div class="card-body">
									        			${item.gcatalogue}
									        			<p class="card-text item-itemLabel">${item.icatalogue}</p>
									        			<p class="card-text item-itemNo">${item.item_no} ${item.item_no2}</p>
									        			<p class="card-text item-price"><span class="item-price-label">${response.currcode}</span>${priceFormatter.format(item.price)}</p>
									     			</div>
										    	</div>
										  	</a>
										</div>`;
						html += htmlSegment;
					});
				}

				document.getElementById('item-card-container').innerHTML = html;

				populateItemPaginationData(response.totalItems, response.itemsPerPage);
			} else {
				toggleError();
			}
		}

		xhr.send();
	} catch (error) {
		console.log(error);
	}
}

// Item List Pagination
async function populateItemPaginationData(totalItems, itemsPerPage) {
	try {
		// Get currPage -- Default
		let currPage = 0;
		if (params.has("currPage") && params.get("currPage") != "") {
			currPage = parseInt(params.get("currPage"));
		} else {
			currPage = 1;
		}

		// Calculate total pages
		let totalPages = parseInt(totalItems / itemsPerPage);
		if ((totalItems % itemsPerPage) != 0) { totalPages += 1; }

		// Generate HTML
		let html = '';
		let htmlSegment = '';

		// Previous button
		if (currPage == 1) {
			htmlSegment = `<li class="page-item disabled">
				      		<span class="page-link" tabindex="-1" aria-disabled="true">&laquo;</span>
				    	</li>`;
		} else {
			htmlSegment = `<li class="page-item" onclick="previousPage()">
				      		<span class="page-link">&laquo;</span>
				    	</li>`;
		}
		html += htmlSegment;
		
		// Generate pagination buttons
		htmlSegment = '';
		if (totalPages > 5) {
			if (currPage < 4) {
				for (let i = 1; i <= 7; i++) {
					if (i == currPage) {
						htmlSegment = `<li class="page-item active"><span class="page-link">${i}</span></li>`;
					} else if (i == 6) {
						htmlSegment = `<li class="page-item ellipsis disabled"><span class="page-link"><i class="fa fa-ellipsis-h" aria-hidden="true"></i></span></li>`;
					} else if (i == 7) {
						htmlSegment = `<li class="page-item" data-page="${totalPages}" onclick="updateItemPaginationData(this)"><span class="page-link">${totalPages}</span></li>`;
					} else {
						htmlSegment = `<li class="page-item" data-page="${i}" onclick="updateItemPaginationData(this)"><span class="page-link">${i}</span></li>`;
					}

					html += htmlSegment;
				}
			} else if (currPage > (totalPages - 3)) {
				let temp = '';
				for (let i = totalPages; i >= totalPages - 7; i--) {
					if (i == currPage) {
						temp = `<li class="page-item active"><span class="page-link">${i}</span></li>`;
					} else if (i == (totalPages - 6)) {
						temp = `<li class="page-item ellipsis disabled"><span class="page-link"><i class="fa fa-ellipsis-h" aria-hidden="true"></i></span></li>`;
					} else if (i == (totalPages - 7)) {
						temp = `<li class="page-item" data-page="1" onclick="updateItemPaginationData(this)"><span class="page-link">1</span></li>`;
					} else {
						temp = `<li class="page-item" data-page="${i}" onclick="updateItemPaginationData(this)"><span class="page-link">${i}</span></li>`;
					}

					htmlSegment = temp + htmlSegment;
				}
				html += htmlSegment;
			} else {
				htmlSegment = `<li class="page-item" data-page="1" onclick="updateItemPaginationData(this)"><span class="page-link">1</span></li>
							<li class="page-item ellipsis disabled"><span class="page-link"><i class="fa fa-ellipsis-h" aria-hidden="true"></i></span></li>`;
				html += htmlSegment;

				for (let i = currPage - 2; i <= currPage + 2; i++) {
					if (i == currPage) {
						htmlSegment = `<li class="page-item active"><span class="page-link">${i}</span></li>`;
					} else {
						htmlSegment = `<li class="page-item" data-page="${i}" onclick="updateItemPaginationData(this)"><span class="page-link">${i}</span></li>`;
					}

					html += htmlSegment;
				}

				htmlSegment = `<li class="page-item ellipsis disabled"><span class="page-link"><i class="fa fa-ellipsis-h" aria-hidden="true"></i></span></li>
							<li class="page-item" data-page="${totalPages}" onclick="updateItemPaginationData(this)"><span class="page-link">${totalPages}</span></li>`;
				html += htmlSegment;
			}
		} else {
			for (let i = 1; i <= totalPages; i++) {
				if (i == currPage) {
					htmlSegment = `<li class="page-item active"><span class="page-link">${i}</span></li>`;
				} else {
					htmlSegment = `<li class="page-item" data-page="${i}" onclick="updateItemPaginationData(this)"><span class="page-link">${i}</span></li>`;
				}

				html += htmlSegment;
			}
		}

		// Next button
		htmlSegment = '';
		if (currPage == totalPages) {
			htmlSegment = `<li class="page-item disabled">
				      		<span class="page-link" tabindex="-1" aria-disabled="true">&raquo;</span>
				    	</li>`;
		} else {
			htmlSegment = `<li class="page-item" onclick="nextPage()">
				      		<span class="page-link">&raquo;</span>
				    	</li>`;
		}
    	html += htmlSegment;

		document.getElementById('pagination-container').innerHTML = html;
		toggleLoading();
	} catch (error) {
		console.log(error);
	}
}

// Update Methods
// Item List
async function updateItemData() {
	try {
		// Reset params
		params.delete("currPage");
		params.delete("search");
		params.delete("sortBy");
		params.delete("filterCat");
		params.delete("filterGroup");
		params.delete("filterDept");

		// Get searched value
		if (document.getElementById('search').value != "") {
			params.set("search", document.getElementById('search').value);
		}

		// Get sortBy value
		document.querySelectorAll(".sortBy").forEach(sort => {
			if (sort.checked) {
				params.set("sortBy",sort.value);
			}
		});
		
		// Get checked cat-filters
		let filterCats = "";
		document.querySelectorAll(".filterCat").forEach(filterCat => {
			if (filterCat.checked) {
				if (filterCats != "") { filterCats += "+"; }
				filterCats += filterCat.value;
			}
		});
		if (filterCats != "") { params.set("filterCat", filterCats); }

		// Get checked group-filters
		let filterGroups = "";
		document.querySelectorAll(".filterGroup").forEach(filterGroup => {
			if (filterGroup.checked) {
				if (filterGroups != "") { filterGroups += "+"; }
				filterGroups += filterGroup.value;
			}
		});
		if (filterGroups != "") { params.set("filterGroup", filterGroups); }

		// Get checked dept-filters
		let filterDepts = "";
		document.querySelectorAll(".filterDept").forEach(filterDept => {
			if (filterDept.checked) {
				if (filterDepts != "") { filterDepts += "+"; }
				filterDepts += filterDept.value;
			}
		});
		if (filterDepts != "") { params.set("filterDept", filterDepts); }

		location.search = "?" + params;
	} catch (error) {
		console.log(error);
	}
}

// Item List Pagination
async function updateItemPaginationData(ref) {
	try {
		// Get curr page
		let currPage = ref.getAttribute("data-page");

		params.set("currPage", currPage);

		location.search = "?" + params;
	} catch (error) {
		console.log(error);
	}
}

async function nextPage() {
	try {
		// Get currPage -- Default
		let currPage = await getCurrPage();

		params.set("currPage", parseInt(currPage) + 1);

		location.search = "?" + params;
	} catch (error) {
		console.log(error);
	}
}

async function previousPage() {
	try {
		// Get currPage -- Default
		let currPage = await getCurrPage();

		params.set("currPage", parseInt(currPage) - 1);

		location.search = "?" + params;
	} catch (error) {
		console.log(error);
	}
}

async function getCurrPage() {
	try {
		// Get currPage -- Default
		if (params.has("currPage") && params.get("currPage") != "") {
			return params.get("currPage");
		} else {
			return "1";
		}
	} catch (error) {
		console.log(error);
	}
}

getCatData();
getGroupData();
getDeptData();
getItemData();