async function jsonPost(url, data)
{
    const options = {
        method: "POST",
        body: JSON.stringify(data)
    }

    try {
        const response = await fetch(url, options)
        const content = await response.json()
        return content
    } catch(e) {
        console.error('error ocurred', e)
    }
}

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

async function drawHistory(messageId=0) {
    let messages = await jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: messageId})
    msgTotal = messages.nextMessageId
    for(let message of messages.data) {
        let msgDiv = document.createElement('div')
        msgDiv.insertAdjacentHTML('beforeend', `
            <small style="color: gold;">${new Date(message.timestamp).toLocaleString()}</small>
            <div style="word-wrap: break-word; color: skyblue;">
                <h4 style="color: mediumseagreen; font-style: italic; display: inline;">${message.nick} :</h4> ${message.message}
            </div>
        `)
        msgDiv.style.width = '100%'
        msgDiv.style.borderBottom = '1px solid grey'
        msgDiv.style.marginBottom = '25px'
        msgScreen.prepend(msgDiv)
    }
    let newStuff = await jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: msgTotal-1})
}
drawHistory()

async function checkNewMessages() {
    let {nextMessageId} = await jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: msgTotal})
    if(nextMessageId > msgTotal) {
        msgTotal = nextMessageId
        return true
    }
    return false
}

async function sendAndCheck() {
    sendMessage(nick, text)
    let oldMsgCount = msgTotal
    checkNewMessages()
    drawHistory(msgTotal - (msgTotal-oldMsgCount))
}

async function checkLoop() {
    while(true) {
        await delay(5000)
        let oldMsgCount = msgTotal
        if(checkNewMessages()) {
            drawHistory(msgTotal - (msgTotal-oldMsgCount))
        }
    }
}
checkLoop()

function isFilled(field) {
    if(field !== '' && !/^[\s]*$/.test(field)) {
        return true
    }
    return false
}

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

let msgScreen = document.getElementById('msgField')
let msgTotal = 0

let nickInput = document.getElementById('nickbox')
let msgInput = document.getElementById('msgbox')
let sendBtn = document.getElementById('sendBtn')
sendBtn.disabled = true

let nick = ''
let text = ''

nickInput.oninput = () => {
    nick = nickInput.value;
    isFilled(nick) && isFilled(text)? sendBtn.disabled = false : sendBtn.disabled = true 
}
msgInput.oninput = () => {
    text = msgInput.value; 
    isFilled(nick) && isFilled(text)? sendBtn.disabled = false : sendBtn.disabled = true 
} 
sendBtn.onclick = () => sendAndCheck()
