
// chatV1()
function chatV1() {

    async function jsonPost(url, data) {
        return new Promise((resolve, reject) => {
            let x = new XMLHttpRequest() 
            x.onerror = () => reject(new Error('jsonPost failed'))
            x.open("POST", url, true)
            // x.setRequestHeader('Content-Type', 'application/json')
            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'))
                }
            }
        })
    }
    // jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: "ууу", message: 'УУУУУУУ'})
    
    function sendMessage(nick, message) {
        let data    = {func: "addMessage", nick: nick, message: message, author: 'chat'}
        jsonPost("http://students.a-level.com.ua:10012", data).then(res => console.log(res))
    }

    function cleanUp(text) {
        if (typeof text !== 'string')
            return text
        if (text.match(/<script/i)){
            let el = document.createElement('div')
            el.innerText = text
            return `<h1>НАС ЛОМАЮТ!!</h1><pre>${el.innerHTML}</pre>`
        }
        return text
    }
    
    let nextMessageId = 0
    function getMessages() {
        let data    = {func: "getMessages", messageId: nextMessageId, author: 'chat'}
        jsonPost("http://students.a-level.com.ua:10012", data).then(result => {
            // console.log(result.data)
            for (const msg of result.data) {
                const msgDiv = document.createElement('div')
                msgDiv.innerHTML = `<b>${cleanUp(msg.nick)}</b>:${cleanUp(msg.message)}`    
                area.prepend(msgDiv)
            }
            nextMessageId = result.nextMessageId  
            // console.log(nextMessageId)
        })  
    }
    getMessages()
    
    btn.addEventListener("click", () => {
        sendMessage(user.value, msg.value)
        getMessages()
    })
    
    setInterval(getMessages, 2000)
}



chatV2()
function chatV2() {

    async function jsonPost(url, data) {    
        try {
            let response = await fetch(url, {
                method: 'POST',
                // headers: {
                // 'Content-Type': 'application/json'
                // },
                body: JSON.stringify(data)
            })           
            if (response.status === 200) {
                return await response.json()
            } else if (response.status != 200) {
                return new Error('status is not 200')
            }
        } catch (err) {
            return new Error('jsonPost failed')
        }
    }      
    
    async function sendMessage(nick, message) {
        let data    = {func: "addMessage", nick: nick, message: message, author: 'chat'}
        try {
            let res = await jsonPost("http://students.a-level.com.ua:10012", data)
            console.log(res)
        } catch (err) {
            console.log(err)        
        }
    }
        
    function cleanUp(text) {
        if (typeof text !== 'string') {
            return text
        }
        if (text.match(/<script/i)){
            let el = document.createElement('div')
            el.innerText = text
            return `<h1>НАС ЛОМАЮТ!!</h1><pre>${el.innerHTML}</pre>`
        }
        return text
    }

    function decorateLinks(text) {
        const linkRegEx = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/
        const youtubeRegEx = /http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?/

        let matchLink = text.match(linkRegEx)
        let matchYoutube = text.match(youtubeRegEx)
        console.log(matchLink)
        if (matchLink) {
            let [link] = matchLink
            if (link) {
                let newLink = `<a href="${link}" style="color:blue">${link}</a>`
                let newText = null
                newText = text.replace(link, newLink)
                if (matchYoutube) {
                    let [, youtubeKey] = matchYoutube
        
                    if (youtubeKey) {
                        return `${newText} <br/> <iframe width="560" height="315" 
                        src="https://www.youtube.com/embed/${youtubeKey}" title="YouTube video player" 
                        frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; 
                        picture-in-picture" allowfullscreen></iframe>`
                    } 
                } else {
                    return newText
                }
            }

        } else {
            return text
        }
    }
    
    let nextMessageId = 0
    async function getMessages() {
        let data    = {func: "getMessages", messageId: nextMessageId, author: 'chat'}
        try {
            let result = await jsonPost("http://students.a-level.com.ua:10012", data)
            for (const msg of result.data) {
                const msgDiv = document.createElement('div')
                msgDiv.className = 'input_message'
                msgDiv.innerHTML = `<div class="message_content"><b>${cleanUp(msg.nick)}</b>:<br/>  ${decorateLinks(cleanUp(msg.message))}</div>`  
                const timeDiv = document.createElement('div')
                timeDiv.className = 'message_time'
                let msgDate = new Date(msg.timestamp)
                function addZero(str) {
                    let string = String(str)
                    if (string.length === 1) {
                        let newStr = '0' + string
                        return newStr
                    } else {
                        return string
                    }
                }
                timeDiv.innerText = `${addZero(msgDate.getHours())}:${addZero(msgDate.getMinutes())}  ${addZero(msgDate.getDate())}.${addZero(msgDate.getMonth())}`
                msgDiv.append(timeDiv)
                area.prepend(msgDiv)
            }
            nextMessageId = result.nextMessageId  
        } catch (err) {
            console.log(err)        
        }
    }

    async function sendAndCheck() {
        await Promise.all([
            sendMessage(user.value, msg.value),
            getMessages()
        ])
    }    
    
    btn.addEventListener("click", () => {
        sendAndCheck()
    })
    getMessages()

    async function checkLoop() {
        let delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
        let inf = true
        while (inf) {
            await delay(2000)
            getMessages()
        }
    }
    checkLoop()
}
