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

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

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

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

#include "game/client/Client.h"

namespace td {
namespace render {

void TowerGui::initWidgets() {
    m_MainMenu = std::make_unique<td::gui::MainMenu>(m_Client.get());
    m_GameMenu = std::make_unique<td::gui::GameMenu>(m_Client.get());
    m_FrameMenu = std::make_unique<td::gui::FrameMenu>(m_Client.get());
    m_UpdateMenu = 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();
    if (m_Client->isConnected())
        m_GameMenu->render();
    else
        m_MainMenu->render();

    m_FrameMenu->render();
    m_UpdateMenu->render();

    endFrame();
}

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

} // namespace render
} // namespace td
