const toastContainer = document.createElement('section');
let toastCounter = 0;

document.body.onload = function(){
	addToastContainer();
}

function addToastContainer(){
	toastContainer.classList.add('toast-container');

	// Add the toast container before the first child of body
	document.firstElementChild.insertBefore(toastContainer, document.body);
}

function randomToast(){
	const toasts = ['You\'ve done an error', 'Yea, it\'s broken, try later', 'Yeeheehee, I am the Grinch witch', 'Sucessfully added', 'Thank you!'];
	newToast(toasts[Math.floor(Math.random() * (toasts.length - 1))]);
}

function newToast(innerText){
	let toast = createToast(innerText);
	addToast(toast);
}

async function addToast(toast){
	toastContainer.appendChild(toast);
	countToasts();

	await new Promise(r => setTimeout(r, 2400));

	// May have been removed by user
	if(document.getElementById(toast.id)){
		toastContainer.removeChild(toast);
	}
}

function createToast(innerText){
	// Output so that screenreaders announce it
	let toast = document.createElement('output');
	let toastInner = document.createElement('div');
	toast.appendChild(toastInner);
	// For screenreaders again, output may not exist
	toast.setAttribute('role','status');

	// Set an Id, so that it can be user removed, etc.
	let toastId = 'toast_'+toastCounter;
	toastCounter++;

	toastInner.innerText = innerText;
	toastInner.classList.add('toast__inner');
	toast.classList.add('toast');
	toast.setAttribute('id', toastId);

	return toast;
}

function countToasts(){
	let toasts = document.getElementsByClassName('toast');
	let toastCounter2 = 0;
	for (const toast of toasts) {
		toastCounter2++;
		if(toastCounter2 > 5){
			let rToast = document.getElementById('toast_'+(toastCounter-5));
			if(rToast){
				toastContainer.removeChild(rToast);
			}
		}
	}
}

