const API_URL = "http://students.a-level.com.ua:10012"

function jsonPost(url, data) {
  return fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  }).then((response) => {
    if (!response.ok) {
      throw Error(response.statusText);
    }
    return response.json();
  }).catch(function (error) {
    console.log(error);
  });
}

function delay(ms) {
  function executor(fulfill, reject) {
    setTimeout(() => fulfill(ms), ms);
  }
  return new Promise(executor);
}

let messagesContainer = document.getElementById('messages');
let messageId = 0;
async function getMessages(messageId) {
  jsonPost(API_URL, { func: 'getMessages', messageId }).then(response => {
    response.data.forEach(element => {
      let messageEl = document.createElement('div');
      messagesContainer.append(messageEl);
      messageEl.classList.add('message');
      let nickEl = document.createElement('div');
      nickEl.classList.add('nick');
      nickEl.innerText = element.nick;
      messageEl.append(nickEl);
      let timestampEl = document.createElement('div');
      timestampEl.classList.add('time');
      const date = new Date(element.timestamp);
      timestampEl.innerText = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
      messageEl.append(timestampEl);
      let messageTextEl = document.createElement('div');
      messageTextEl.innerText = element.message;
      messageTextEl.classList.add('text');
      messageEl.append(messageTextEl);
    });
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
    messageId = response.nextMessageId;
  });
}
getMessages(messageId);

async function checkLoop() {
  while (true) {
    await delay(2000);
    getMessages(messageId);
  }
}

checkLoop();

async function sendMessage(nick, message) {
  const body = {
    func: 'addMessage',
    nick: nick || 'Anonymous',
    message: message,
  };
  return await jsonPost(API_URL, body);
}

async function sendAndCheck(nick, message) {
  const response = await sendMessage(nick, message);
  if (response.nextMessageId > messageId) {
    getMessages(messageId);
  }

}

let submitButton = document.getElementById('send');
submitButton.addEventListener('click', () => {
  let nickEl = document.getElementById('nick');
  let messageEl = document.getElementById('message');
  sendAndCheck(nickEl.value, messageEl.value);
  nickEl.value = '';
  messageEl.value = '';
});