var TabController: TabController = {
	elements: {
		menu: document.querySelector('.tabmenu'),
		pages: document.querySelector('.tabpages')
	},

	setTitle(title: string) {
		var titleElement = document.querySelector('title');
		titleElement.innerText = `Undecked - ${title}`;
	},

	show(tabname: string) {
		TabController.elements.menu.querySelectorAll('.item').forEach((element: HTMLDivElement) => {
			var tab = element.getAttribute('tab');
			if (tab == tabname) element.classList.add('active');
			else element.classList.remove('active');
		});
		TabController.elements.pages.querySelectorAll('.item').forEach((element: HTMLDivElement) => {
			var tab = element.getAttribute('tab');
			if (tab == tabname) element.classList.add('active');
			else element.classList.remove('active');
		});

		if (tabname == 'pages') {
			var pageID = PageHandler.currentPageID;

			history.pushState(null, null, `/pages/pageID`);
			TabController.setTitle(`Page ${pageID}`);
		} else {
			history.pushState(null, null, `/${tabname}`);

			TabController.setTitle(tabname.charAt(0).toUpperCase() + tabname.slice(1));
		}
	},

	registerListeners() {
		TabController.elements.menu.querySelectorAll('.item').forEach((element: HTMLDivElement) => {
			var tab = element.getAttribute('tab');
			element.onclick = () => {
				TabController.show(tab);
			};
		});
	},

	init() {
		var args = window.location.pathname.split('/');
		if (args.length > 0) args.splice(0, 1);

		var tab = args.length > 0 ? args[0] : null;
		var subTab = args.length > 1 ? args[1] : null;

		if (PageList.order != null) {
			if (tab != undefined && tab.length > 0) {
				if (tab == 'pages') {
					var valid = PageList.select(subTab);

					if (valid) {
						var index = PageList.order.indexOf(subTab);
						PageHandler.request(PageList.order[index], index);
						TabController.show('pages');
					} else {
						PageHandler.request(PageList.order[0], 0);
						TabController.show('pages');
					}
				} else {
					PageHandler.request(PageList.order[0], 0);
					TabController.show(tab);
				}
			} else {
				PageList.firstRender = false;
				PageHandler.request(PageList.order[0], 0);
				TabController.show('pages');
			}
		} else
			setTimeout(() => {
				TabController.init();
			}, 200);
	}
};

TabController.init();
TabController.registerListeners();

interface TabController {
	elements: {
		menu: HTMLDivElement;
		pages: HTMLDivElement;
	};

	setTitle: (title: string) => void;
	show: (tabname: string) => void;
	registerListeners: () => void;

	init: () => void;
}
