// Copyright (C) 2020 Daniel Mall

// sokol system
#include "sokol_app.h"
#include "sokol_gfx.h"
#include "sokol_time.h"
#include "sokol_glue.h"
#include "imgui.h"
#define SOKOL_IMGUI_IMPL
#include "sokol_imgui.h"

#include "CDemoGlobals.h"

static uint64_t last_time = 0;

//! color for background frame
static sg_pass_action gs_pass_action;

bool my_tool_active = true;

void Init(void)
{
	// call sokol sg_setup once in the application

	// setup sokol-gfx
	sg_desc windowDesc = { };
	windowDesc.context = sapp_sgcontext();
	sg_setup(&windowDesc);

	// setup sokol-time
	stm_setup();

	// setup sokol-audio
	global()->m_pAudio->AudioDeviceOpen();

	// setup sokol-imgui
	// use sokol-imgui with all default-options (we're not doing
	// multi-sampled rendering or using non-default pixel formats)
	simgui_desc_t simgui_desc = { };
	simgui_setup(&simgui_desc);
}

//! primary callback for rendering a frame
void Frame()
{
	const int width = sapp_width();
	const int height = sapp_height();
	const double delta_time = stm_sec(stm_laptime(&last_time));
	simgui_new_frame(width, height, delta_time);

	{
		ImGui::SetNextWindowPos(ImVec2(5, 5), ImGuiCond_FirstUseEver);

		// Create a window called "My First Tool", with a menu bar.
		ImGui::Begin("CogDemoImgui", &my_tool_active, ImGuiWindowFlags_MenuBar);
		if (ImGui::BeginMenuBar())
		{
			if (ImGui::BeginMenu("Demo"))
			{
				if (ImGui::MenuItem("Imgui (GUI Interface)")) { global()->m_dispatch.m_nDemoSelected = eDemoDispatchId::nDemoIdImgui; }
				if (ImGui::MenuItem("Triangle (Classic OpenGL)")) { global()->m_dispatch.m_nDemoSelected = eDemoDispatchId::nDemoIdTriangle; }
				if (ImGui::MenuItem("Spokes (Audio Mixer)")) { global()->m_dispatch.m_nDemoSelected = eDemoDispatchId::nDemoIdSpokes; }
				ImGui::EndMenu();
			}

			ImGui::EndMenuBar();
		}
		ImGui::End();
	}

	// initial clear color
	gs_pass_action.colors[0].action = SG_ACTION_CLEAR;
	gs_pass_action.colors[0].value = { 0.0f, 0.5f, 0.7f, 1.0f };
	global()->m_dispatch.PassAction(gs_pass_action);

	// the sokol_gfx draw pass
	sg_begin_default_pass(&gs_pass_action, width, height);
	global()->m_pAudio->PushAudioToDeviceQueue();
	global()->m_dispatch.Frame();
	simgui_render();
	sg_end_pass();
	sg_commit();
}

//! primary callback for events
void EventInput(const sapp_event* event)
{
	simgui_handle_event(event);
	global()->m_dispatch.EventInput(event);
}

//! primary callback for cleanup
void Cleanup(void)
{
	// shut down sokol-imgui
	simgui_shutdown();

	// shut down sokol-audio
	global()->m_pAudio->AudioDeviceClose();

	// shut down sokol-gfx
	sg_shutdown();
}

sapp_desc sokol_main(int argc, char* argv[])
{
	(void)argc; (void)argv;
	sapp_desc desc = { };
	desc.init_cb = Init;
	desc.frame_cb = Frame;
	desc.cleanup_cb = Cleanup;
	desc.event_cb = EventInput;
	desc.width = 1024;
	desc.height = 768;
	desc.gl_force_gles2 = true;
	desc.window_title = "CogDemoImgui";
	desc.ios_keyboard_resizes_canvas = false;
	return desc;
}
