// GLOBAL VARIABLES

let allTheInterim = "";
let finalTranscripts = "";
let interimTranscripts = "";

let speech = document.getElementById("result");
let process = document.getElementById("process");

// TEXT STORAGE

let textStorage = localStorage.getItem("speech");
speech.innerHTML = textStorage;

// RESET STORAGE

let resetStorage = document.getElementById("reset");

resetStorage.addEventListener("click", () => {
	// Reset everything
	allTheInterim = "";
	finalTranscripts = "";
	interimTranscripts = "";
	speech.innerHTML = "";
	textStorage = "";
	localStorage.setItem("speech", "");
});

// SAVE FILE

let saveButton = document.getElementById("save");
saveButton.addEventListener("click", () => {
	download("speech.html", localStorage.getItem("speech"));
});

function download(filename, text) {
	var element = document.createElement("a");
	element.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent(text));
	element.setAttribute("download", filename);

	element.style.display = "none";
	document.body.appendChild(element);

	element.click();

	document.body.removeChild(element);
}

// START LISTENING

startConverting();

function startConverting() {
	if ("webkitSpeechRecognition" in window) {
		let speechRecognizer = new webkitSpeechRecognition() || new SpeechRecognition();

		speechRecognizer.continuous = true;
		speechRecognizer.interimResults = true;
		speechRecognizer.lang = "en-US";
		speechRecognizer.start();

		finalTranscripts = "";

		// EVENTS

		// ON END
		speechRecognizer.onend = function () {
			console.log("Speech recognition service disconnected");
			speechRecognizer.start();
		};

		// ON SOUND START
		speechRecognizer.onsoundstart = function () {
			console.log("Some sound is being received");
		};

		// ON ERROR
		speechRecognizer.onerror = function (event) {};

		// ON RESULT
		speechRecognizer.onresult = function (event) {
			interimTranscripts = "";

			for (let i = event.resultIndex; i < event.results.length; i++) {
				let transcript = event.results[i][0].transcript;
				// console.log(event.results[i][0]);
				transcript.replace("\n", "<br>");
				if (event.results[i].isFinal) {
					finalTranscripts += transcript;
				} else {
					interimTranscripts += transcript;
					allTheInterim += `<span style="opacity: ${
						event.results[i][0].confidence + 0.3
					}">${interimTranscripts}</span> `;
				}
			}
			process.innerHTML = allTheInterim;
			let final =
				finalTranscripts + '<span class="interim">' + interimTranscripts + "</span>";

			speech.innerHTML = final;

			textStorage = final;
			console.log(textStorage);
			localStorage.setItem("speech", final);
		};
	} else {
		speech.innerHTML = "At the moment this works only in Chrome, sorry";
	}
}
