let bot = new RiveScript();

const message_container = document.querySelector('.messages');
const form = document.querySelector('form');
const input_box = document.querySelector('input');

const brains = [
    './begin.rive',
    './brain.rive'
];

bot.loadFile(brains).then(botReady).catch(botNotReady);

form.addEventListener('submit', (e) => {
  e.preventDefault();
  selfReply(input_box.value);
  input_box.value = '';
});

function getRandomNumber(start, end, increments) {
    var numbers = [];
    for(var n = start; n <= end; n += increments) {
        numbers.push(n);
    }

    var randomIndex = Math.floor(Math.random() * numbers.length);
    return numbers[randomIndex];
}

function getWelcomeText() {
    fetch('./welcome.txt')
    .then(response => response.text())
    .then((data) => {
      const textArray = data.split(/\r?\n/);
      textArray.forEach(function (item, index) {
          botReply(item);
          document.title = '(2) - Smart Speaker Theatre';
        });
  
    })

}


function botReply(message){
  message_container.innerHTML += `<div class="bot">${message}</div>`;
  location.href = '#edge';
}

function selfReply(message){
  message_container.innerHTML += `<div class="self">${message}</div>`;
  location.href = '#edge';

  bot.reply("local-user", message).then(function(reply) {
    //botReply(reply);
    setTimeout(function() {
        botReply(reply);
    }, getRandomNumber(600, 1800, 400)); // Random delay for answer between 225 and 1000 ms, with 200ms increments
    document.querySelector(".chat").scrollTop = document.querySelector(".chat").scrollHeight;
    document.title = '(1) - Smart Speaker Theatre'
});
}

function botReady(){
  bot.sortReplies();
// The welcome text is parsed from welcome.txt
// Each new line in that file, becomes a text bubble
    getWelcomeText();
  
}

function botNotReady(err){
  console.log("An error has occurred.", err);
}

function Title(){
    setTimeout(function() {
        document.title = 'Smart Speaker Theatre'
    }, 500);
    
}

document.addEventListener("mousemove", Title);