#define SOKOL_IMPL

#include "mirage.h"

#include <iostream>
#include <thread>

#include "core/window/render_window.h"
#include "misc/mirage_scoped_duration_timer.h"

void mirage_log(const char* tag, uint32_t log_level, uint32_t log_item_id, const char* message_or_null,
                uint32_t line_nr, const char* filename_or_null, void* user_data) {
	if (log_level == 0) // painc
		std::cerr << "sg: " << message_or_null << std::endl;
	else if (log_level == 1) // error
		std::cerr << "sg: " << message_or_null << std::endl;
	else if (log_level == 2) // warning
		std::cout << "sg: " << message_or_null << std::endl;
	else if (log_level == 3) // info
		std::clog << "sg: " << message_or_null << std::endl;
}

void mirage_app::init() {
	duration_type duration;
	{
		mirage_scoped_duration_timer timer(duration);

		last_time = get_current_time();
		render_context = mirage_create_render_context();
		render_context->init();
		const sg_desc desc = {
			.logger = {
				.func = mirage_log,
				.user_data = nullptr
			},
			.environment = render_context->get_environment(),
		};
		sg_setup(desc);
		render_context->end_init();
	}
	// 初始化用时
	std::cout << "mirage: " << "Initialization took " << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << "ms" << std::endl;
}

void mirage_app::run() {
	while (!mirage_window::get_windows().empty()) {
		duration_type delta_time = get_current_time() - last_time;
		mirage_window::poll_events();
		render_context->tick(delta_time);

		last_time = get_current_time();
		// std::this_thread::sleep_for(std::chrono::milliseconds(1));
		std::this_thread::yield();
	}
	render_context->cleanup();
	delete render_context;
}
