let chatLog = [];

function attachChat(room) {
    let chatButton = document.getElementById("chat-submit");
    chatButton.addEventListener("click", event => {
        let chatInput = document.getElementById("chat-input");
        if(chatInput.value.length > 3) {
            sendMessage(chatInput.value);
            chatInput.value = "";
        }
        chatInput.focus();
    });

    let chatInput = document.getElementById("chat-input");
    chatInput.addEventListener("keyup", event => {
        if(event.keyCode == 13) { //enter
            chatButton.click();
        }
    });

    updateChatLogDisplay();
}

function updateChatLogDisplay() {
    let chatLogDisplay = document.getElementById("chat-log");
    if(chatLogDisplay) {
        chatLogDisplay.innerHTML = formatChat(chatLog);
    }
}

function formatChat(log) {
    let output = [];
    for(let i = 0; i < chatLog.length; i++) {
        let message = chatLog[i];
        output.push(`${message.user}: ${message.message}`)
    }
    return output.join("\n");
}

function sendMessage(message) {
    broadcast(userData, message);
}

function receiveMessage(source, message) {
    if(source != userData) {
        toastMessage(`${source.name}: ${message}`, source.style);
    }
    chatLog.push({user: source.name, userId: source.id, message: message});
    updateChatLogDisplay();
}

function broadcast(source, message) {
    receiveMessage(source, message);
}