var Icons: Icons = {
	elements: {
		container: document.querySelector('.panel.icons').querySelector('.list')
	},

	resizeTimeout: null,

	currentSelected: null,

	loadOnScreen() {
		Icons.elements.container.querySelectorAll('.icon').forEach((icon: HTMLDivElement) => {
			var position = icon.getBoundingClientRect();

			// checking for partial visibility
			if (position.top < window.innerHeight && position.bottom >= 0) {
				if (icon.hasAttribute('notloaded')) {
					icon.removeAttribute('notloaded');
					var iconID = icon.getAttribute('iconID');

					var whiteImg: HTMLImageElement = icon.querySelector('img.white');
					var blackImg: HTMLImageElement = icon.querySelector('img.black');

					whiteImg.src = `/stc/materialicons/white/${iconID}.png`;
					blackImg.src = `/stc/materialicons/black/${iconID}.png`;
					whiteImg.style.opacity = '1';
					blackImg.style.opacity = '0';
				}
			}

			icon.onclick = () => Icons.select(icon.getAttribute('iconID'));
		});
	},

	listeners() {
		var counter = 0;
		Icons.elements.container.onscroll = () => {
			counter++;
			if (counter > 5) {
				Icons.loadOnScreen();
				counter = 0;
			}
			clearTimeout(Icons.resizeTimeout);
			Icons.resizeTimeout = setTimeout(() => {
				Icons.loadOnScreen();
			}, 100);
		};
		// Icons.loadOnScreen();
	},

	select(iconID: string, ignoreUpdate: boolean = false) {
		var icons = Icons.elements.container.querySelectorAll('.icon');
		for (let i = 0; i < icons.length; i++) {
			var testIconID = icons[i].getAttribute('iconID');
			if (iconID != testIconID) icons[i].classList.remove('selected');
			else icons[i].classList.add('selected');
		}
		Icons.currentSelected = iconID;

		if (ignoreUpdate == false) Editor.registerChange();
	},

	deselect() {
		var icons = Icons.elements.container.querySelectorAll('.icon');
		for (let i = 0; i < icons.length; i++) icons[i].classList.remove('selected');

		Icons.currentSelected = null;
	}
};

Icons.listeners();

interface Icons {
	elements: {
		container: HTMLDivElement;
	};

	resizeTimeout: any;

	currentSelected: string;

	loadOnScreen: () => void;
	listeners: () => void;
	select: (iconID: string, ignoreUpdate?: boolean) => void;
	deselect: () => void;
}
