{% extends 'base.html' %}

{% block title %} Logs Viewer {% endblock %}

{% block extra_head %}
	<style type="text/css">
		#logs-content {
			height: 500px;
			overflow: auto;
			white-space: pre-wrap;
			flex-grow: 1;
		}
		@media (max-width: 991px) {
			html, body, #logs-content {
				height: 100%;
				width: 100%;
				max-width: none;
			}

			#logs-content {
				margin-top: 0;
			}
		}

		.log-type-DEBUG {
			float: left;
			color: blue;
		}
		.log-type-INFO {
			float: left;
			color: green;
		}
		.log-type-WARN {
			float: left;
			color: #FFC107;
		}
		.log-type-ERROR {
			float: left;
			color: red;
		}

		.log-timestamp {
			font-size: 12px;
			color: gray;
			float: right;
		}

		#logs-level-dropdown {
			border: 1px solid #ccc;
			border-radius: 4px;
			padding: 4px 8px;
			font-size: 16px;
			font-family: Arial, sans-serif;
			color: #333;
			background-color: #fff;
			box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
			transition: border-color 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
		}

		#logs-level-dropdown:focus {
			outline: none;
			border-color: #007bff;
			box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 0 2px rgba(0, 123, 255, 0.5);
		}

		#logs-level-form label {
			font-size: 16px;
			font-family: Arial, sans-serif;
			font-weight: bold;
			margin-right: 8px;
			color: #333;
		}

		#logs-level-form-container {
			display: inline-block;
		}

		#logs-level-form,
		#logs-level-dropdown {
			display: inline-block;
		}

		.status-indicator {
			display: flex;
			align-items: center;
		}

		.status-indicator h5 {
			margin: 0;
		}

		.status-indicator .dot {
			display: inline-block;
			width: 10px;
			height: 10px;
			margin-right: 5px;
			background-color: #7CFC00;
			border-radius: 50%;
			animation: pulse 1s ease-out infinite;
		}

		.status-indicator.active .dot {
			background-color: #7CFC00;
			animation-name: pulse-active;
		}

		.status-indicator.inactive .dot {
			background-color: #fc0000;
			animation: pulse-inactive 1s ease-out infinite;
		}

		@keyframes pulse-active {
			0% {
				box-shadow: 0 0 0 0px rgba(124, 252, 0, 0.4);
			}
			100% {
				box-shadow: 0 0 0 10px rgba(124, 252, 0, 0);
			}
		}

		@keyframes pulse-inactive {
			0% {
				box-shadow: 0 0 0 0px rgba(252, 0, 0, 0.4);
			}
			100% {
				box-shadow: 0 0 0 10px rgba(252, 0, 0, 0);
			}
		}
	}
	</style>

{% endblock %}

{% block content %}
<div class="container" id="content">
	<div class="row align-items-center">
		<div class="col">
			<h3>Logs</h3>
		</div>
		<div class="col-auto">
			<form id="logs-level-form">
				<label for="logs-level-dropdown">Set Log <abbr title="Each log level includes all levels above it.">Level</abbr>:</label>
				<select id="logs-level-dropdown" name="logs-level-dropdown">
					<option value="DEBUG">Debug</option>
					<option value="INFO">Info</option>
					<option value="WARN">Warn</option>
					<option value="ERROR">Error</option>
				</select>
			</form>
		</div>
		<div class="col-auto">
			<button id="start-button" class="btn btn-success">Start</button>
			<button id="stop-button" class="btn btn-danger">Stop</button>
			<button id="clear-button" class="btn btn-warning">Clear Logs</button>
		</div>
	</div>
	<div class="row">
		<div class="col">
			<div class="bg-light rounded p-3" id="logs-content">
			</div>
		</div>
	</div>
	<div class="row">
		<div class="col">
			<div class="status-indicator" id="status-indicator">
				<span class="dot"></span>
				<h5 id="status-indicator-text"></h5>
			</div>
		</div>
	</div>
</div>

<script>
	// Define the log levels and their corresponding filtering conditions
	const logLevels = {
		'DEBUG': 	['DEBUG', 'INFO', 'WARN', 'ERROR'],
		'INFO': 	['INFO', 'WARN', 'ERROR'],
		'WARN': 	['WARN', 'ERROR'],
		'ERROR': 	['ERROR']
	};

	let eventSource = new EventSource('/stream');
	let historic_logs = [];

	eventSource.onopen = function() {
		handle_sse_start(event);
	};

	eventSource.onmessage = function(event) {
		handle_sse_messages(event);
	};

	eventSource.onerror = function(event) {
		handle_sse_errors(event);
	};

	// Handle filter dropdown change event	
	$('#logs-level-dropdown').change(function() {
		log_level = $(this).val();
		$('#logs-content').empty();
		localStorage.setItem('log_level', log_level);
		historic_logs = [];

		// Restart the SSE connection
		eventSource.close();
		eventSource = new EventSource('/stream');

	// Set up event listeners on the new EventSource object
		eventSource.onopen = function(event) {
			handle_sse_start(event);
		}

		eventSource.onmessage = function(event) {
			handle_sse_messages(event);
		}

		eventSource.onerror = function(event) {
			handle_sse_errors(event);
		}
	});

	// Handle Start button click event
	$('#start-button').click(function() {
		{%- if platform == "discord" -%}
		var num = prompt("What's your Discord's server ID? ");
		var url = "start?server=" + num;
		{%- else -%}
		var url = "start";
		{%- endif -%}
		$.ajax({ 
			type: "GET",
			url: url,
			beforeSend: function() {
				document.getElementById('start-button').disabled = true;
			},
			success: function(data){
				// alert('started');
			},
			error: function(xhr){
				// alert('not started');
				document.getElementById('start-button').disabled = false;
			}
		});
	});

	// Handle Stop button click event
	$('#stop-button').click(function() {
		$.ajax({ 
			type: "GET",
			url: "stop",
			success: function(data){
				eventSource.close();
				// alert('stopped');
			},
			error: function(xhr){
				// alert('not stopped');
			}
		});
	});

	// Handle clear logs button click event
	$('#clear-button').click(function() {
		$.ajax({ 
			type: "GET",
			url: "clear",
			success: function(data){
				$('#logs-content').empty();
			},
			error: function(xhr){
				// alert('not clear');
			}
		});
	});

	function handle_sse_messages(event){
		var message = JSON.parse(event.data);
		var messageId = message.id;

		// Get the selected log level
		var logLevel = $('#logs-level-dropdown').val();
		var logLevel_stored = localStorage.getItem("log_level");

		if (logLevel === null || logLevel_stored === null) {
			$("#logs-level-dropdown").val("INFO").change();
			logLevel = "INFO";
		}
		else if (logLevel !== logLevel_stored) {
			$("#logs-level-dropdown").val(logLevel_stored).change();
			logLevel = logLevel_stored;
		}

		// Check if the message type matches the filtering condition
		if (!historic_logs.includes(messageId) && logLevels[logLevel].includes(message.type)) {
			// Store to the historics
			historic_logs.push(messageId);

			// Format the new log
			var logString = '<div>\
			<span class="log-type-'+message.type+'">[' + message.type + '] </span>\
			<span class="float-start">' + message.content + '</span>\
			<span class="log-timestamp">' + message.timestamp + '</span>\
			</div>';

			// Append the new log
			$('#logs-content').append(logString);

			// Scroll to latest message
			var logsContent = document.getElementById("logs-content");
			logsContent.scrollTop = logsContent.scrollHeight;
		}
	};

	function handle_sse_start(event){
		console.log("Getting server updates");
		setStatusIndicatorActive(true);
		document.getElementById('start-button').disabled = false;
		document.getElementById('stop-button').disabled = false;
	};

	function handle_sse_errors(event){
		console.log('EventSource error:', event);
		setStatusIndicatorActive(false);
		document.getElementById('start-button').disabled = true;
		document.getElementById('stop-button').disabled = true;

	};

	// Add or remove the "active" class to the status indicator
	function setStatusIndicatorActive(isActive) {
		const indicator = document.querySelector('#status-indicator');
		if (isActive) {
			document.getElementById('status-indicator-text').innerHTML = 'Framework status: Active';
			indicator.classList.add('active');
			indicator.classList.remove('inactive');
		}
		else {
			document.getElementById('status-indicator-text').innerHTML = 'Framework status: Inactive';
			indicator.classList.add('inactive');
			indicator.classList.remove('active');	
		}
	}

</script>
{% endblock %}