import type { TTS } from "web/alerts/TTSTypes";

class TTSManager {
	private busy: boolean;
	private ttsQueue: TTS[];
	private audio: HTMLAudioElement;

	constructor() {
		this.busy = false;
		this.ttsQueue = [];
		this.audio = new Audio();
		document.body.appendChild(this.audio);
	}

	private async playAudio(url: string) {
		return new Promise((res) => {
			this.audio.src = url;
			this.audio.load();
			this.audio.play();
			this.audio.onended = res;
			this.audio.onpause = res;
		});
	}

	private async playTTS(tts: TTS) {
		this.busy = true;
		switch (tts.type) {
			case "microsoft":
				await this.playAudio(
					`https://tetyys.com/SAPI4/SAPI4?text=${tts.text}&voice=${tts.voice}&pitch=${tts.pitch}&speed=${tts.speed}`,
				);
				break;
			case "dectalk":
				await this.playAudio(`http://tts.cyzon.us/tts?text=${tts.text}`);
				break;
		}

		const newTTS = this.ttsQueue.shift();
		if (!newTTS) {
			this.busy = false;
			return;
		} else this.playTTS(newTTS);
	}

	public queueTTS(input: TTS) {
		if (this.busy) this.ttsQueue.push(input);
		else this.playTTS(input);
	}

	public endTTS() {
		this.audio.pause();
	}
}

export default new TTSManager();
