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

    let interval = setInterval(async () => {
        await updMessages()
    }, 3000)
    sendBtn.onclick = async () => {
       let resp = await jsonPost("http://students.a-level.com.ua:10012",
            messageDataCreator($msg.value)
        )
        $msg.value = ''
    }
    return list
}

function getSomeData(data) {
    let currentData = data
    return function (){
        return currentData
    }
}

async function chatMaker() {
    showMessagesList(await fetchData())
}
chatMaker()



