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 login = document.getElementById('inputName')
let msg = document.getElementById('inputMsg')
let send = document.getElementById('send')
let chat = document.getElementById('chat')
let messageId = 0;


async function sendMessage(nick , message ){
        await jsonPost("http://students.a-level.com.ua:10012", {
        func: 'addMessage', 
        nick: login.value, 
        message: msg.value})
}


async function getMessages(){
        jsonPost("http://students.a-level.com.ua:10012", {
        func: "getMessages", messageId: 0
    }).then((a) => {
        showChat(a.data, chat)
    })
}

function showChat(data, container){
    let sortedData = data.sort((a, b) => b.timestamp - a.timestamp)
    for(let message of sortedData){
        let div = document.createElement('div')
        let spanName = document.createElement('b')
        let spanMsg = document.createElement('span')
        let spanTime = document.createElement('mark')
        let time = new Date(message.timestamp)

        container.appendChild(div)
        div.appendChild(spanName)
        div.appendChild(spanMsg)
        div.appendChild(spanTime)
        spanName.innerHTML = message.nick + ': '
        spanMsg.innerHTML = message.message + '   '
        spanTime.innerHTML = time.toGMTString()
    } 
}

async function sendAndCheck(){
    sendMessage();
    getMessages();
    msg.value = ""
}

btn.onclick = () => {
    return sendAndCheck()
}


setInterval(getMessages, 5000)