let speech = new SpeechSynthesisUtterance();

let voices = [];
window.speechSynthesis.onvoiceschanged = () => {
  voices = window.speechSynthesis.getVoices();
  speech.voice = voices[0];
  let voiceSelect = document.querySelector("#voices");
  voices.forEach((voice, i) => (voiceSelect.options[i] = new Option(voice.name, i)));
};

document.querySelector("#rate").addEventListener("input", () => {
  const rate = document.querySelector("#rate").value;
  speech.rate = rate;
  document.querySelector("#rate-label").innerHTML = rate;
});

document.querySelector("#volume").addEventListener("input", () => {
  const volume = document.querySelector("#volume").value;
  speech.volume = volume;
  document.querySelector("#volume-label").innerHTML = volume;
});

document.querySelector("#pitch").addEventListener("input", () => {
  const pitch = document.querySelector("#pitch").value;
  speech.pitch = pitch;
  document.querySelector("#pitch-label").innerHTML = pitch;
});

document.querySelector("#voices").addEventListener("change", () => {
  speech.voice = voices[document.querySelector("#voices").value];
});

document.querySelector("#start").addEventListener("click", () => {
  speech.text = "Init complete";
  window.speechSynthesis.speak(speech);
  $("#start").hide();
  init();
});

document.querySelector("#pause").addEventListener("click", () => {
  window.speechSynthesis.pause();
});

document.querySelector("#resume").addEventListener("click", () => {
  window.speechSynthesis.resume();
});

document.querySelector("#cancel").addEventListener("click", () => {
  window.speechSynthesis.cancel();
});

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

reload = true;

function init() {
    setInterval(function(){
      if (reload) {
        $.ajax({
            datatype: "application/json",
            url: "/tts_queue",
            cache: false,
            success: function(result) {
              if (result) {
                json = JSON.stringify(result, null, 4);
                var json = JSON.parse(json);
                var firstKey = Object.keys(json)[0];

                if (json[firstKey]) {
                  console.log(json[firstKey]);;
                  speech.text = json[firstKey];;
                  window.speechSynthesis.speak(speech);
                  reload = false;
                  speech.onend = function(event) {
                      console.log(`Utterance has finished being spoken after ${event.elapsedTime} microseconds.`);
                      fetch("/tts_done?id="+firstKey);
                      reload = true;
                      sleep(1000);
                  }
                }
              }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                console.log("Error");
                console.log(xhr.status);
                console.log(thrownError);
            }
        });
      }
    }, 1000);
};
