let messageId = 0;

send.onclick = () => {
    jsonPost('http://students.a-level.com.ua:10012', {
        func: 'addMessage',
        nick: nick.value,
        message: message.value,
    });
};


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

setInterval(() => {
    jsonPost('http://students.a-level.com.ua:10012', {
        func: 'getMessages',
        messageId: messageId,
    }).then((result) => {
        for (let key in result.data) {

            let div = document.createElement('div');

            div.textContent = `${result.data[key].nick}:${result.data[key].message}`;
            let time = document.createElement('span');

            let timeOfSending = new Date(result.data[key].timestamp);
            let minutes = '0' + timeOfSending.getMinutes();
            let seconds = '0' + timeOfSending.getSeconds();
            time.textContent = `Date: ${timeOfSending.getDate()}/${timeOfSending.getMonth() + 1}/${timeOfSending.getFullYear()}, time: ${timeOfSending.getHours()}:${minutes.substr(-2)}:${seconds.substr(-2)}`;
            chat.prepend(div);
            chat.prepend(time);
        }

        messageId = result.nextMessageId;
    });
}, 3000);

{

    let messageId = 0;

    send.onclick = async function sendAndCheck() {

        await Promise.all([sendMessage('http://students.a-level.com.ua:10012', {
            func: 'addMessage',
            nick: nick.value,
            message: message.value,
        }), getMessages()]);
    };

    async function sendMessage(url, data) {

        const settings = {
            method: 'Post',
            mode: 'cors',
            cahe: 'no-cache',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            redirect: 'follow',
            referrerPolicy: 'no-referrer',
            body: JSON.stringify(data),
        };

        try {
            let response = await fetch(url, settings);
            return response.json();
        } catch (error) {
            return console.log(error);
        }

    }
}

async function getMessages() {
    await sendMessage('http://students.a-level.com.ua:10012', {
        func: 'getMessages',
        messageId: messageId,
    }).then((resAll) => {
        for (let key in resAll.data) {
            let span = dociment.createElement('div');
            span.className = 'time';

            span.textContent = `${resAll.data[key].nick}: ${resAll.data[key].messge}`;
            let time = document.createElement('span');
            time.className = 'time';

            let timeOfSending = new Date(resAll.data[key].timestamp);
            let minutes = '0' + timeOfSending.getMinutes();
            time.textContent = `${timeOfSending.getDate()}.${timeOfSending.getMonth() + 1}.${timeOfSending.getFullYear()} ${timeOfSending.getHours()}:${minutes.substr(-2)}`;
            chat.prepend(time);
            chat.prepend(span);
            chat.prepend(document.createElement('hr'));
        }

        messageId = resAll.nextMessageId;
        console.log(messageId);

    });
}

(function checkLoop() {
    setInterval(async () => {
        await getMessages();
    }, 3000);
})();
