#include "DeerStudio.h"

#include "DeerStudio/EditorEngine.h"

// TMP
#include "DeerStudio/Editor/Icons.h"
#include "DeerStudio/Fonts.h"
#include "DeerStudio/Style.h"
// TMP

#include "Deer/Application.h"
#include "Deer/Path.h"

#include "Deer/DataStore.h"
#include "Deer/Voxel.h"

int main(int, char**) {
	Deer::Path projectPath = Deer::Application_tmp::getWindow().folderDialog(nullptr);
	if (projectPath.empty()) return 0;

	Deer::DataStore::rootPath = projectPath;
	Deer::DataStore::loadVoxelsData();
	Deer::DataStore::loadVoxelsAspect();

    Deer::Application_tmp::initWindow();

	Deer::DataStore::generateTextureAtlas();
	Deer::DataStore::loadVoxelsShaders();
	
	Deer::EditorEngine::initialize();

	Deer::Icons::setupIcons();

	Deer::initializeFonts();

	SetupImGuiStyle();

	ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(20, 20));

    Deer::Application_tmp::run();

	Deer::EditorEngine::deinitialize();
}

namespace Deer {
    namespace DeerStudio {
        void onUpdate() {
		    if (Scene::getExecutingState())
		    	Scene::tickExecution();
            
		    if (VoxelWorld::isInitialized())
		    	VoxelWorld::bakeNextChunk();	
        }

        void onRender() {
		    static bool opt_fullscreen = true;
		    static bool opt_padding = false;
		    static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None;

		    ImGuiWindowFlags window_flags =
		        ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking;

		    {
		    	const ImGuiViewport* viewport = ImGui::GetMainViewport();
		    	ImGui::SetNextWindowPos(viewport->WorkPos);
		    	ImGui::SetNextWindowSize(viewport->WorkSize);
		    	ImGui::SetNextWindowViewport(viewport->ID);
		    	window_flags |= ImGuiWindowFlags_NoTitleBar |
		    	                ImGuiWindowFlags_NoCollapse |
		    	                ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
		    	window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus |
		    	                ImGuiWindowFlags_NoNavFocus;
		    	window_flags |= ImGuiWindowFlags_NoBackground;
		    }

		    static bool p_open = true;
		    ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
		    ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
		    ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
		    ImGui::Begin("DockSpace Demo", &p_open, window_flags);
		    ImGui::PopStyleVar();
		    ImGui::PopStyleVar(2);

		    ImGuiID dockspace_id = ImGui::GetID("DockSpace Demo");
		    ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags);

		    if (ImGui::BeginMenuBar()) {
		    	drawMenuBar();
		    	ImGui::EndMenuBar();
		    }

		    for (auto Panel : Panels) {
		    	Panel->onImGui();
		    }

		    // ---- PanelS -----
		    TerrainEditor::onImGui();
		    viewport_onImGui();
		    EditorEngine::render();
		    // ---- PanelS -----
		    Scene::gizmoRenderer.refresh();
		    ImGui::End();
        }

	    void onEvent(Event& e) {
	    	viewport_onEvent(e);
	    }
    }
}  // namespace Deer