let timeConverter = timestamp => {
    let date = new Date(timestamp);
    let optionsDate = { year: "numeric", month: 'long', day: 'numeric' }
    let optionsTime = { hour: '2-digit', minute: '2-digit' }
    let convertedDate = date.toLocaleDateString("ua-UA", optionsDate) + "  " + date.toLocaleTimeString("ua-UA", optionsTime)

    return convertedDate;
}

let del = 350;
let msgId = 0;

let updateScroll = () => {
    setTimeout(() => chatWindow.scrollTop = chatWindow.scrollHeight, del)

    if (del === 350) {
        del = 0;
    }
}

let chatWindowShower = (data, parent) => {
    for (let key of data) {
        let div = document.createElement("div");
        let spanNick = document.createElement("span");
        let spanMsg = document.createElement("span");
        let spanDate = document.createElement("span");
        spanNick.innerText = key.nick;
        spanMsg.innerText = key.message;
        spanDate.innerText = timeConverter(key.timestamp);

        div.append(spanNick, spanMsg, spanDate)

        parent.append(div)
    }
}

let delay = ms => {
    return new Promise(ok => {
        setTimeout(() => ok(ms), ms)
    })
}

//stage 0 - 4
/*
function jsonPost(url, data) {
    return new Promise((resolve, reject) => {
        var x = new XMLHttpRequest();
        x.onerror = () => reject(new Error('jsonPost failed'))
        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'))
            }
        }
    })
}

btn.onclick = e => {
     if (nick.value !== "" && msg.value !== "") {
         jsonPost("http://students.a-level.com.ua:10012", { func: 'addMessage', nick: nick.value, message: msg.value })

         msg.value = ""
     }
 }

let getMsg = () => {
    jsonPost("http://students.a-level.com.ua:10012", { func: "getMessages", messageId: msgId })
        .then(json => {

            if (json.nextMessageId !== msgId) {
                updateScroll()
                msgId = json.nextMessageId;
            }
            chatWindowShower(json.data, chatWindow)
        })
}

setInterval(getMsg, 2000)
*/

//stage 5-6
async function jsonPost(url, data) {
    const response = await fetch(url, { method: 'POST', body: JSON.stringify(data) });
    let result = await response.json()
    return result;
}

async function sendMessage(nck, msg) {
    let result = await jsonPost("http://students.a-level.com.ua:10012", { func: 'addMessage', nick: nck, message: msg });
    return result;
}

async function getMessages() {
    let json = await jsonPost("http://students.a-level.com.ua:10012", { func: "getMessages", messageId: msgId });

    if (json.nextMessageId !== msgId) {
        updateScroll()
        msgId = json.nextMessageId;
    }

    chatWindowShower(json.data, chatWindow)
}

async function sendAndCheck() {
    await sendMessage(nick.value, msg.value)
    await getMessages()
}

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

}

btn.onclick = e => {
    if (nick.value !== "" && msg.value !== "") {
        sendAndCheck()
    }
}

checkLoop()