import * as storage from "./storage.js";

const TRACKED_STORAGE_NAME = "/drops/tracked/";

export let showOnlyTracked = false;
export let kindFilter = new Set();

export function init() {
	loadTracked();

	const onlyTrackedFilter = document.querySelector(
		'input[name="onlyTracked"]',
	);

	onlyTrackedFilter.addEventListener("input", function () {
		showOnlyTracked = this.checked ? true : false;
		filter();
	});

	const kindFilters = document.querySelectorAll(
		'input[type="checkbox"][name="kindFilter"]',
	);

	kindFilters.forEach(function (item, index) {
		item.addEventListener("input", function () {
			if (this.checked) {
				kindFilter.add(this.value);
			} else {
				kindFilter.delete(this.value);
			}
			filter();
		});
	});
}

function filter() {
	const categories = document.querySelectorAll(".category-wrapper");

	for (const category of categories) {
		let isTracked = category.dataset["isTracked"] == "true";
		let kind = category.dataset["matKind"];
		let type = category.dataset["matType"];

		category.style.display = "";

		if (showOnlyTracked && !isTracked) {
			category.style.display = "none";
		}

		if (kindFilter.size > 0) {
			if (!kindFilter.has(kind)) {
				category.style.display = "none";
			}
		}
	}
}

function loadTracked() {
	const categories = document.querySelectorAll(".category-wrapper");
	let updates = 0;

	for (const category of categories) {
		let id =
			TRACKED_STORAGE_NAME +
			category.dataset["matKind"] +
			"-" +
			category.dataset["matType"];

		let isTracked = storage.get(id) === "true";
		if (isTracked) {
			category.dataset["isTracked"] = true;
			let trackButton = category.querySelector(".category button");
			updateTrackedState(trackButton, isTracked);
			updates += 1;
		}
	}

	if (updates > 0) {
		filter();
	}
}

export function track(element) {
	let parent = element.parentElement.parentElement;
	let id =
		TRACKED_STORAGE_NAME +
		parent.dataset["matKind"] +
		"-" +
		parent.dataset["matType"];

	let isTracked = parent.dataset["isTracked"] ?? false;
	isTracked = isTracked === "true" ? false : true;

	if (isTracked) {
		storage.set(id, true);
	} else {
		storage.remove(id);
	}

	parent.dataset["isTracked"] = isTracked;
	updateTrackedState(element, isTracked);
	filter();
}

function updateTrackedState(element, isTracked) {
	element.innerHTML = isTracked ? "Stop tracking" : "Start tracking";
	element.style["border-bottom-color"] = isTracked ? "#a00" : "#0a0";
}
