/* 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'))
            }
        }
    })
} */
let sendButton = document.getElementById('send');
let nick = document.getElementById('nick');
let message = document.getElementById('msg');
let chat = document.getElementById('chat');
sendButton.addEventListener('click', () =>{
    let nickValue = nick.value;
    let messageValue = message.value;
   sendMessage(nickValue,messageValue);
    message.value = '';
    
 })
/* jsonPost("http://students.a-level.com.ua:10012")
    .then((result) => {
        /* console.log(result.data);
        let chat = document.getElementById('chat');
        for(let message of result.data){
            chat.innerHTML = `${message.nick} : ${message.message}`;
        } */
       /*  getMessage();
        console.log(nextMessageId);
    })  */
    /* .then((data)=> getMessage(data)) */

async function sendAndCheck(nick,message){
    await sendMessage(nick,message);
    await getMessage();
}
async function getMessage(messageId = 0){
   /*  jsonPost2("http://students.a-level.com.ua:10012",{func: "getMessages", messageId:messageId})
        .then((result) => {
          let chat = document.getElementById('chat');
            let reversedData = result.data.reverse();
            reversedData.forEach(element => {
                let divMsg = document.createElement('div');
                let nickSpan = document.createElement('span');
                let messageSpan = document.createElement('span');
                nickSpan.innerHTML += element.nick;
                messageSpan.innerHTML += `: ${element.message}`;
                divMsg.appendChild(nickSpan,);
                divMsg.appendChild(messageSpan);
                chat.append(divMsg);
            });
        })  */
        let res = await jsonPost2("http://students.a-level.com.ua:10012",{func: "getMessages", messageId:messageId})
        /* let chat = document.getElementById('chat'); */
            chat.innerHTML = '';
            let reversedData =  res.data.reverse();
            reversedData.forEach((element) => {
              /*   let divMsg = document.createElement('div');
                let nickSpan = document.createElement('span');
                let messageSpan = document.createElement('span');
                nickSpan.innerHTML += element.nick;
                messageSpan.innerHTML += `: ${element.message}`;
                divMsg.appendChild(nickSpan,);
                divMsg.appendChild(messageSpan);
                chat.append(divMsg); */
                drawMessages(element);
            });
        /* let prevId = res.nextMessageId;
        let currentId = messageId;
        if(currentId<prevId){
            let result = await jsonPost2("http://students.a-level.com.ua:10012",{func: "getMessages", messageId:currentId+1});
            let reversed = result.data.reverse();
            reversed.forEach((element) => {
                drawMessages(element);
            })
        } */
     }
function drawMessages(element){
    let divMsg = document.createElement('div');
    let nickSpan = document.createElement('span');
    let messageSpan = document.createElement('span');
    nickSpan.innerHTML += element.nick;
    messageSpan.innerHTML += `: ${element.message}`;
    divMsg.appendChild(nickSpan,);
    divMsg.appendChild(messageSpan);
    chat.append(divMsg);
}
async function sendMessage(userNick,userMessage) {
     
        /* jsonPost2("http://students.a-level.com.ua:10012",{func: "addMessage",nick:userNick,message: userMessage})
            .then((result) => {
                console.log(result);
                getMessage(result.nextMessageId);
            }); */

        let res = await jsonPost2("http://students.a-level.com.ua:10012",{func: "addMessage",nick:userNick,message: userMessage})
        getMessage(res.nextMessageId);
        message.value = '';
     }
const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms));
async function checkLoop(){
    await getMessage()
        .then(() => delay(2000))
        .then(checkLoop);
}
getMessage(); 
async function jsonPost2(url,data){
         let result  =  await fetch(url,{
        method: 'POST',
        body: JSON.stringify(data)
    });
    if(result.status == 200){
        let json =  await result.json();
    return json
    } else{
        throw new Error(result.statusText);
    }
}

checkLoop();
/* getMessage(); */
/* jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: "Anon", message: 'Я не умею копипастить в консоль, зато умею жать красную кнопку.'}) */