App.UI.Theme = (function() {
	// NOTE: Due to browser limitations it is not possible to retrieve the path of selected files, only the filename.
	// We therefore expect all files to be located in the same directory as the HTML file. Selected files from somewhere
	// else will simply not be loaded or if a file in the correct place has the same name, it will be loaded instead.
	let currentThemeElement = null;
	let devTheme = null;

	// reload theme on page reload
	$(document).on(":passagestart", () => {
		if (currentThemeElement === null && V.theme !== 0 && V.theme !== undefined) {
			load(V.theme);
		}
	});

	return {
		selector: selector,
		devTheme: reloadDevTheme,
		onLoad: onLoad
	};

	/**
	 * @returns {HTMLDivElement}
	 */
	function selector() {
		const div = document.createElement("div");

		const selector = document.createElement("input");
		selector.type = "file";
		selector.accept = ".css";
		div.append(selector);

		div.append(App.UI.DOM.link("Apply", () => {
			unload();
			if (selector.files.length > 0) {
				const themeFile = selector.files[0];
				load(themeFile.name);
			}
		}), " ", App.UI.DOM.link("Unload", unload));

		return div;
	}

	/**
	 * @param {string} filename or filepath relative to the HTML file.
	 */
	function load(filename) {
		V.theme = filename;

		currentThemeElement = newTheme(filename);

		document.head.appendChild(currentThemeElement);
	}

	function unload() {
		if (currentThemeElement !== null) {
			document.head.removeChild(currentThemeElement);
			currentThemeElement = null;
			V.theme = 0;
		}
	}

	/**
	 * Unloads current dev theme and loads new theme if specified.
	 * @param {string} [filename]
	 */
	function reloadDevTheme(filename) {
		if (devTheme !== null) {
			document.head.removeChild(devTheme);
			devTheme = null;
		}

		if (filename !== undefined) {
			devTheme = newTheme(filename);

			document.head.appendChild(devTheme);
		}
	}

	function newTheme(filename) {
		const theme = document.createElement("link");
		theme.setAttribute("rel", "stylesheet");
		theme.setAttribute("type", "text/css");
		theme.setAttribute("href", `./${filename}`);
		return theme;
	}

	/**
	 * @param {object} V
	 */
	function onLoad(V) {
		if (V.theme !== 0) {
			load(V.theme);
		}
	}
})();

src/gui/theming.js