#include "log_viewer.h"

#include "../lib/math.h"
#include <stdio.h>
#include "../gui/gui.h"

LogViewer LogViewer::Init(Logger *logger)
{
	LogViewer viewer;
	viewer.logger = logger;
	return viewer;
}

void LogViewer::Print_New_Messages_On_Console()
{
	u64 message_count = Logger_MessageCount(logger);
	if(message_count <= 0)
		return;

	u64 last_message_index = message_count - 1;
	LogEntry *last_message = Logger_MessageAt(logger, last_message_index);
	u64 id_diff = last_message->id - next_id_to_print_on_console;
	u64 index_start = (last_message_index > id_diff) ? (last_message_index - id_diff) : 0;

	u64 max_id = next_id_to_print_on_console;
	for(int i = index_start; i < message_count; i++)
	{
		LogEntry *entry = Logger_MessageAt(logger, i);
		if(entry->id >= next_id_to_print_on_console)
		{
			// printf("%lu ", entry->id);
			// if     (entry->level >= LOG_DEBUG)   printf("DEBUG");
			// else if(entry->level >= LOG_INFO)    printf("INFO");
			// else if(entry->level >= LOG_WARNING) printf("WARNING");
			// else if(entry->level >= LOG_ERROR)   printf("ERROR");
			// printf(": ");
			fprintf((entry->level < LOG_INFO ? stderr : stdout), "%s\n", entry->message);

			max_id = maximum(max_id, entry->id + 1);
		}
	}
	next_id_to_print_on_console = max_id;
}

void LogViewer::Draw_New_Messages_On_GUI()
{
	u64 messages_to_draw = 5;

	u64 message_count = Logger_MessageCount(logger);
	if(message_count <= 0)
		return;

	Rect r = { .position = {0, (f32)global_gui_state.default_context.height}, .size = {0,0} };
	messages_to_draw = minimum(messages_to_draw, message_count);
	for(u64 i = 0; i < messages_to_draw; i++)
	{
		u64 index = message_count - 1 - i;
		LogEntry *entry = Logger_MessageAt(logger, index);
		char id_string[24]; sprintf(id_string, "%lu: ", entry->id);

		v2 id_size      = gui_text_compute_size(id_string);
		v2 message_size = gui_text_compute_size(entry->message);

		r.position.y -= maximum(id_size.y, message_size.y);
		r.position.x = 0;
		r.size = id_size;
		gui_text(r, id_string);

		r.position.x += id_size.x;
		r.size = message_size;
		gui_text(r, entry->message);
	}
}
