var recognizing = false;
var ignore_onend;
var start_timestamp;

const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
 
var recognition = new SpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;

recognition.onstart = function() {
  recognizing = true;
  //showInfo('info_speak_now');
  console.log('LISTENING...');
};

recognition.onerror = function(event) {
  console.error((event.timeStamp - start_timestamp), event.error);
  if (event.error == 'no-speech') {
    //showInfo('info_no_speech');
    ignore_onend = true;
  }
  if (event.error == 'audio-capture') {
    //showInfo('info_no_microphone');
    ignore_onend = true;
  }
  if (event.error == 'not-allowed') {
    if (event.timeStamp - start_timestamp < 100) {
      //showInfo('info_blocked');
    } else {
      //showInfo('info_denied');
    }
    ignore_onend = true;
  }
};

recognition.onend = function() {
  console.log('ENDED');
  recognizing = false;
};

recognition.onresult = function(ev) {
  const results = ev.results;
  //console.log(results.length, results);
  
  if (typeof(results) == 'undefined') {
    recognition.onend = null;
    recognition.stop();
    console.log('browser does not support');
    return;
  }
  
  var interim_transcript = '';
  for (var i = ev.resultIndex; i < results.length; ++i) {
    console.log('result ' + i, results[i].isFinal, parseInt(ev.timeStamp), results[i][0])
    if (results[i].isFinal) {
      final_transcript += results[i][0].transcript;
    } else {
      interim_transcript += results[i][0].transcript;
    }
  }
  console.log('interim', interim_transcript);
  console.log('final', final_transcript);
};

function startButton(event) {
  if (recognizing) {
    recognition.stop();
    return;
  }
  final_transcript = '';
  recognition.lang = 'en-US';
  recognition.start();
  ignore_onend = false;
  //showInfo('info_allow');
  start_timestamp = event.timeStamp;
}

document.onclick = startButton;