let $nickname = document.querySelector('#nick')
let sendBtn = document.querySelector('#sendButton');
let $msg = document.querySelector('#msg')
let msgHolder = document.querySelector('#msgHolder')

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'))
            }
        }
    })
}

// function messageDataCreator(message) {
//     return {
//         func: 'addMessage',
//         nick: $nickname.value,
//         message: message,
//     }
// }
//
function showMessagesList(arr) {
    let $container = document.createElement('div')
    for(let msg of arr) {
        let $div = document.createElement('div')
        $div.className = 'msg'
        let $p1 = document.createElement('p')
        let $p2 = document.createElement('p')
        $p1.innerHTML = msg.nick + ':'
        $p2.innerHTML = msg.message
        $div.append($p1, $p2)
        $container.append($div)
    }
    msgHolder.prepend($container)
}

    async function getMessages() {
        let id = 0;
        let resp = await jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: id})
        let {data, nextMessageId} = await resp
        id = nextMessageId
        let list = data.slice(data.length - 50).reverse()
        showMessagesList(list)
        if(nextMessageId > id) {
            id = nextMessageId
            showMessagesList(data)
        }
    }

    // let interval = setInterval(async () => {
    //
    // }, 3000)


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

sendBtn.onclick = sendAndCheck()
    async function sendAndCheck() {
        await getMessages()
        await sendMessage($nickname.value, $msg.value)
        $msg.value = ''
    }

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



