let messageId = 0;

async function sendMessage() {
  let data = {
    func: 'addMessage',
    nick: `${nick.value}`, 
    message: `${message.value}`,
  };
  try {
    let response = await fetch('http://students.a-level.com.ua:10012', {
      method: 'POST',
      body: JSON.stringify(data),
    });
    
    let result = await response.json(); 
    messageId = result.nextMessageId; 
  }
  catch  (err) { 
    console.log(err);
  }
    
}

function buildChat (obj) {
  let arr = obj['data'];
   
  for (let i = 0; i < arr.length; i++) { 
    const b = document.createElement('b');
    const p = document.createElement('p');
    chat.prepend(p);
    p.append(b);
    b.innerHTML = (`${arr[i]['nick']} :`);
    p.append(`${arr[i]['message']}`);
  }
}

async function getMessages() {
  try {
    let data = {
      func: "getMessages", 
      messageId: messageId,
    };
    let response = await fetch('http://students.a-level.com.ua:10012',{
      method: 'POST',
      body: JSON.stringify(data), 
    });

    let result = await response.json(); console.log(result);
    buildChat(result);
  }
  catch (err) {
    console.log(err);
  }
}

async function sendAndCheck() {
  Promise.all([sendMessage(), getMessages()])
  nick.value = '';
  message.value = '';
}

sendMes.onclick = sendAndCheck;


setInterval(getMessages, 3000);