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



let sendBtn = document.getElementById('sendButton')
sendBtn.innerHTML = "Send"
let nickInput = document.getElementById('nickInput')
let msgInput = document.getElementById('msgInput')
nickInput.style.width = '99.5%'
msgInput.style.width = '99.5%'
sendBtn.style.width = '100%'
nickInput.style.height = '40px'
msgInput.style.height = '40px'
msgInput.style.marginTop = '20px'
sendBtn.style.marginTop = '20px'
sendBtn.style.height = '40px'
nickInput.style.fontSize = '20px'
msgInput.style.fontSize = '20px'
sendBtn.style.fontSize = '20px'

// default
// sendBtn.onclick = function sendMsg () {
//     let nick = document.getElementById('nickInput').value
//     let msg = document.getElementById('msgInput').value
//     jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: nick, message: msg })
//     document.getElementById('nickInput').value = ''
//     document.getElementById('msgInput').value = ''
// }

// function addMsg () {
//     let startMsg = 0;
//     setInterval(function(){
//         jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: startMsg}).then (result => {console.log(result.data)
//         for(startMsg in result.data) {
//             let chat = document.getElementById('chat')
//             let divMessage = document.createElement('div')
//             divMessage.style.border = '1px solid black'
//             divMessage.style.borderRadius = '10px'
//             divMessage.style.marginTop = '10px'
//             divMessage.style.backgroundColor = '#1E90FF'
//             divMessage.style.color = 'white'
//             let pMsg = document.createElement('p')
//             pMsg.innerHTML = result.data[startMsg].nick + ':' + ' ' + result.data[startMsg].message
//             pMsg.style.marginLeft = '20px'
//             pMsg.style.fontSize = '30px'
//             let time = document.createElement('p')
//             time.innerHTML = `${new Date(result.data[startMsg].timestamp).toLocaleString()}`
//             time.style.marginLeft = '20px'
//             divMessage.append(pMsg)
//             divMessage.append(time)
//             chat.prepend(divMessage)
//         }
//         startMsg = result.nextMessageId})
//     },2000)
// }
// addMsg()

//async
async function jsonPost(url, data)
{
    let res = await fetch(url, {
        method: 'POST', 
        body: JSON.stringify(data) 
      });
      return await res.json();}

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

  let nickVal = nickInput.value
  let msgVal = msgInput.value
  
  async function sendMessage(nick,message) {
    jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: nickInput.value, message: msgInput.value })
    document.getElementById('nickInput').value = ''
    document.getElementById('msgInput').value = ''
    }


    async function getMessages() {
        let startMsg = 0
        jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: startMsg})
        .then(result=>{console.log(result.data)
        for(startMsg in result.data){
            let chat = document.getElementById('chat')
            let divMessage = document.createElement('div')
            divMessage.style.border = '1px solid black'
            divMessage.style.borderRadius = '10px'
            divMessage.style.marginTop = '10px'
            divMessage.style.backgroundColor = '#1E90FF'
            divMessage.style.color = 'white'
            let pMsg = document.createElement('p')
            pMsg.innerHTML = result.data[startMsg].nick + ':' + ' ' + result.data[startMsg].message
            pMsg.style.marginLeft = '20px'
            pMsg.style.fontSize = '30px'
            let time = document.createElement('p')
            time.innerHTML = `${new Date(result.data[startMsg].timestamp).toLocaleString()}`
            time.style.marginLeft = '20px'
            divMessage.append(pMsg)
            divMessage.append(time)
            chat.prepend(divMessage)
        }
    })
    } 


    async function sendAndCheck(){
        await sendMessage(nickVal,msgVal)
        await getMessages()
    }

    sendBtn.onclick = () => {
        sendAndCheck()
    }

    async function checkLoop (){
        delay(3000)
        getMessages()
    }

    checkLoop()






