export class MessageBar {
	#container;
	#stack = [];

	constructor(containerId, defaultMessage="") {
		//console.log("Build infobar in:", containerId);
		const container = document.getElementById(containerId);
		if(!container) throw new Error("Le conteneur désigné n'existe pas");
		this.#container = container;
		if(defaultMessage) this.push({msg:defaultMessage, TTL:-1, priority:9999});
	}

	push(msgObj) {
		//console.log("Add new message:", msgObj);
		// Supprimer le message en cours n'a aucune priorité (écrasement)
		//if(this.#stack.length>1) if(this.#stack[0].priority>=900) console.log("Shift stack",this.#stack.shift());
		this.#stack.push({'msg':msgObj.msg, 'type':msgObj.type?? 'info', TTL:msgObj.TTL??5, 'priority':msgObj.priority?? 5, 'id':msgObj.id?? 0});
		this.#refresh();
		// Effacter le message s'il a une expiration
		if(msgObj.TTL) if(msgObj.TTL>0) setTimeout(() => { this.remove(msgObj.msg);}, msgObj.TTL*1000);
	}

	async #refresh() {
		//console.log("MessageBar - refresh");
		// Tri de la stack message selon les priorités
		this.#stack.sort(function compare(a, b) {return a.priority - b.priority;});
		//console.log("... Sorted stack:",this.#stack);
		// Message à afficher
		var firstMsg = (this.#stack.length>0)? this.#stack[0].msg : '';
		if(firstMsg!=this.#container.innerText) {
			// Affichage du message en haut de pile (si différent de celui en place)
			this.#container.innerText = firstMsg;
		}
	}

	async remove(critera) {
		//console.log("MessageBar - remove:", critera);
		const varType = typeof critera;
		switch(varType) {
			case 'number':
				this.#stack = this.#stack.filter(obj => obj.id !== critera);
				break;
			case 'string':
				this.#stack = this.#stack.filter(obj => obj.msg !== critera);
				break;
		}
		this.#refresh();
	}
}