/*
 * TowerGui.cpp
 *
 *  Created on: 5 nov. 2020
 *      Author: simon
 */

#include "client/render/gui/TowerGui.h"
#include "client/render/gui/imgui/imgui.h"

#include "client/render/gui/MainMenu.h"
#include "client/render/gui/GameMenu.h"
#include "client/render/gui/FrameMenu.h"
#include "client/render/gui/UpdateMenu.h"

#include "imgui/imgui_impl_opengl3.h"
#include "imgui/imgui_impl_sdl.h"

#include "client/Client.h"

namespace td {
namespace render {

void TowerGui::InitWidgets() {
	m_GuiManager.AddWidget(std::make_unique<td::gui::MainMenu>(m_Client.get()));
	m_GuiManager.AddWidget(std::make_unique<td::gui::GameMenu>(m_Client.get()));
	m_GuiManager.AddWidget(std::make_unique<td::gui::FrameMenu>(m_Client.get()));
	m_GuiManager.AddWidget(std::make_unique<td::gui::UpdateMenu>(m_Client.get()));
}

TowerGui::TowerGui(SDL_Window* sdl_window, SDL_GLContext glContext, td::render::Renderer* renderer) : m_Window(sdl_window),
m_GlContext(glContext), m_Renderer(renderer), m_Client(std::make_unique<client::Client>(m_Renderer)) {
	IMGUI_CHECKVERSION();
	ImGui::CreateContext();
	ImGui::StyleColorsDark();
	ImGui_ImplSDL2_InitForOpenGL(m_Window, m_GlContext);
	ImGui_ImplOpenGL3_Init();
	ImFontConfig c;
	c.SizePixels = 25;
	ImGui::GetIO().Fonts->AddFontDefault(&c);
	InitWidgets();
}

void TowerGui::BeginFrame() {
	ImGui_ImplOpenGL3_NewFrame();
	ImGui_ImplSDL2_NewFrame();
	ImGui::NewFrame();
}

void TowerGui::EndFrame() {
	ImGui::EndFrame();
	ImGui::Render();
	ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}

void TowerGui::Tick() {
	static std::uint64_t lastTime = td::utils::GetTime();
	std::uint64_t time = td::utils::GetTime();

	std::uint64_t delta = time - lastTime;

	m_Client->Tick(delta);

	lastTime = td::utils::GetTime();
}

void TowerGui::Render() {
	Tick();
	BeginFrame();

	m_Client->Render();

	m_GuiManager.RenderWidgets();

	EndFrame();
}

TowerGui::~TowerGui() {
	m_Client->CloseConnection();
	ImGui_ImplOpenGL3_Shutdown();
	ImGui_ImplSDL2_Shutdown();
	ImGui::DestroyContext();
}

} // namespace render
} // namespace td
