function jsonPost(url, data) {
  return new Promise((resolve, reject) => {
    var x = new XMLHttpRequest();
    x.onerror = () => reject(new Error("jsonPost failed"));
    //x.setRequestHeader('Content-Type', 'application/json');
    x.open("POST", url, true);
    x.send(JSON.stringify(data));

    x.onreadystatechange = () => {
      if (x.readyState == XMLHttpRequest.DONE && x.status == 200) {
        resolve(JSON.parse(x.responseText));
      } else if (x.status != 200) {
        reject(new Error("status is not 200"));
      }
    };

    const chat = document.querySelector("#chat");
    chat.style.display = "flex";
    chat.style.flexDirection = "column-reverse";

    const div = document.createElement("div");
    div.style.display = "flex";
    div.style.justifyContent = "space-between";
    div.style.alignItems = "center";
    div.style.margin = "5px";

    const p = document.createElement("p");
    p.style.margin = "5px";

    div.innerText = `${data.nick}: ${data.message}`;
    p.innerText = new Date(data.timestamp);
    console.log(data.timestamp);

    div.appendChild(p);
    chat.appendChild(div);
  });
}

btn.onclick = () => {
  jsonPost("http://students.a-level.com.ua:10012", {
    func: "addMessage",
    nick: inputNick.value,
    message: inputMessage.value,
  });
};
let messageId = 0;
jsonPost("http://students.a-level.com.ua:10012", {
  func: "getMessages",
  messageId,
}).then((d) => {
  messageId = d.nextMessageId;
  for (const key of d.data) {
    const div = document.createElement("div");
    div.style.display = "flex";
    div.style.justifyContent = "space-between";
    div.style.alignItems = "center";
    div.style.margin = "5px";

    const p = document.createElement("p");
    p.style.margin = "5px";
    div.innerText = `${key.nick}: ${key.message}`;
    p.innerText = new Date(key.timestamp);
    div.appendChild(p);
    chat.appendChild(div);
  }
  console.log(d.data);
});
