//Stage 0
// jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: "alex", message: 'simple line'})
//     .then(value => console.log(value), value => console.log(value))
// jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: 0})
//     .then(value => console.log(value))

//Stage 1
let globalQuantityMessages = 0;
(() => {
    let form = document.createElement('div');
    let nick = document.createElement('input');
    let message = document.createElement('textarea');
    let button = document.createElement('button');
    button.textContent = 'Send'
    button.onclick = () => {
        sendAndCheck(nick.value, message.value)
            .then(value => console.log(value), value => console.log(value));
    }
    nick.type = 'text';
    nick.placeholder = 'your nick';
    message.placeholder = 'your message';
    nick.className = 'form__item';
    message.className = 'form__item';
    button.className = 'form__item';
    form.append(nick);
    form.append(message);
    form.append(button);
    document.body.append(form);
    document.body.style.backgroundColor = '#c2bbbb'
})()

async function sendMessage(nick, message) {
    let localQuantityMessages = await jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: nick.toString(), message: message.toString()});
    if (localQuantityMessages['nextMessageId'] > globalQuantityMessages){
        globalQuantityMessages = localQuantityMessages['nextMessageId'] - 1;
    }
}

//Stage 2
async function getMessages() {
    try {
        let localQuantityMessages = await jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages",messageId: 0});
        let div = document.createElement('div');
        globalQuantityMessages = localQuantityMessages['nextMessageId'];
        for (const key in localQuantityMessages['data']) {
            let p = document.createElement('p');
            let date = new Date(localQuantityMessages['data'][key]['timestamp']);
            let formattedTime = date.getDate()+"/"+(date.getMonth()+1)+"/"+date.getFullYear()+
                " "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
            p.innerHTML = `<strong>${localQuantityMessages['data'][key]['nick']}:</strong> ${localQuantityMessages['data'][key]['message']} <sub>${formattedTime}</sub>`;
            div.append(p);
        }
        document.body.append(div);
        return localQuantityMessages['data'];
    }
    catch {
        return new Error('Error in get messages')
    }
}

//Stage 3
async function getNewMessage(){
    try {
        let newQuantityMessages = await jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages",messageId: globalQuantityMessages});
        if (newQuantityMessages['nextMessageId'] > globalQuantityMessages) {
            globalQuantityMessages = newQuantityMessages['nextMessageId'];
            let div1 = document.createElement('div');
            for (const key in newQuantityMessages['data']) {
                let p = document.createElement('p');
                let date = new Date(newQuantityMessages['data'][key]['timestamp']);
                let formattedTime = date.getDate()+"/"+(date.getMonth()+1)+"/"+date.getFullYear()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
                p.innerHTML = `<strong>${newQuantityMessages['data'][key]['nick']}:</strong> ${newQuantityMessages['data'][key]['message']} <sub>${formattedTime}</sub>`;
                div1.append(p);
            }
            document.body.append(div1);
        }
    } catch (e) {
        return new Error('Error in Stage 3, 4')
    }
}

//Stage 4
//setInterval(async () => getNewMessage(), 3000);

//Stage 5
async function sendAndCheck(nick, message) {
    await Promise.all([sendMessage(nick, message), getNewMessage()]);
    // await sendMessage(nick, message).then(value => console.log(value), value => console.log(value));
    // await getNewMessage();
}

async function checkLoop() {
    const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms));
    while(true) {
        await delay(3000).then(() => getNewMessage().then(value => console.log(value), value => console.log(value)))
    }
}
checkLoop().then(value => console.log(value), value => console.log(value));

//Stage 6
async function jsonPost(url, data) {
    return new Promise(  async (resolve, reject) => {
        let response = await fetch(url, {method: 'POST', body: JSON.stringify(data)});
        (response.ok) ? resolve(await response.json()) : reject(new Error('jsonPost failed'));
    });
}






