function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
}

$(document).ready(async () => {
    const wsConnectionString = (await fetch(`/api/websocketConnection`)).text()
    const socket = new WebSocket(wsConnectionString);
    let lastMessageNumber = 0;
    let page = 20;
    const fetchMoreMessages = async () => {
        if (lastMessageNumber < 0 ) return [];
        let messages = await (await fetch(`/api/getChatMessages/${lastMessageNumber}/${page}`)).json();
        lastMessageNumber = messages.length < page? -1 : lastMessageNumber + messages.length
        return messages
    }

    const appendMessageToChat = (author, content) => {
        const messageDiv = document.createElement('div')
        messageDiv.className = "chat-message"
        messageDiv.textContent = `<${author}> ${content}`
        document.getElementsByClassName("messages-container")[0].appendChild(messageDiv)
    }

    const prependMessageToChat = (author, content) => {
        const messageDiv = document.createElement('div')
        messageDiv.className = "chat-message"
        messageDiv.textContent = `<${author}> ${content}`
        const messageContainer = document.getElementsByClassName("messages-container")[0]
        messageContainer.firstChild.insertAdjacentElement('afterend', messageDiv)
    }

    const onFetchMessageButtonClick = async () => {
        let messages = await fetchMoreMessages(lastMessageNumber, page);
        if (messages.length == 0) return;

        messages.forEach(message => {
            prependMessageToChat(message.author, message.content);
        });
    }

    $("#fetch-messages-button").click(onFetchMessageButtonClick);

    await onFetchMessageButtonClick();
    
    socket.onmessage = message => {
        try {
            message = JSON.parse(message.data)
        } catch(e) {
            console.log(e)
            return;
        }
        appendMessageToChat(message.author, message.content)
    }

    const sendData = async () => {
        const jwt = getCookie("jwt");
        const author = await (await fetch(`/api/getUsername`)).text()
        const content = $("#chat-input").val();

        const message = {
            jwt, author, content
        };

        socket.send(JSON.stringify(message));
        appendMessageToChat(message.author, message.content)
        $("#chat-input").val("")
        let messageContainer = $(".messages-container")
        messageContainer.animate({ scrollTop: messageContainer.prop("scrollHeight")}, 1000);
    }

    $("#send-message-button").click(sendData);

    $('#chat-input').keyup(function(e){
        if(e.keyCode == 13)
        {
            $(this).trigger("enterKey");
        }
    });

    $("#chat-input").bind("enterKey", sendData);
});
