window.addEventListener('load', initChat);

let userName = '';
let messageField = null;
let sendButton = null;

function initChat()
{
	// Send the message when the Send button is pressed
	sendButton = document.getElementById('send');
	sendButton.disabled = true;
	sendButton.addEventListener('click', sendMessage);

	// Send the message when Enter key is pressed in field
	messageField = document.getElementById('message');
	messageField.addEventListener('keyup', (event) =>
	{
		// Disable the Send button when message field is empty
		sendButton.disabled = messageField.value.trim().length === 0;

		// Send a message when there is text and the Enter key is pressed
		if ( ! sendButton.disabled && event.key === "Enter" )
			sendMessage();
	});
}

function sendMessage()
{
	// Get text message from field, and clear the field
	const field = document.getElementById('message');
	const message = field.value;
	field.value = '';

	appendHistory(userName, message, 'user');
}

function appendHistory(label, message, className)
{
	// Add <li> message to the history
	const history = document.getElementById('history');
	// Create a <li><span class="user">user</strong>: message</li> element
	const li = document.createElement('li');

	const span = document.createElement('span');
	span.setAttribute('class', className);
	span.appendChild( document.createTextNode(label) );
	li.appendChild(span);

	const textNode = document.createTextNode(': ' + message);
	li.appendChild(textNode);

	history.appendChild(li);
}

// Called the first time the user sends data: his/her name
function connect()
{
	// Disable controls to avoid user trying to connect twice
	messageField.disabled = true;
	sendButton.disabled = true;
	userName = messageField.value;
	appendHistory('Chat', 'Connecting to server...', 'info');
}
