#include "GamePanel.h"

#include <filesystem>

#include "Deer/Enviroment.h"
#include "Deer/Scene.h"
#include "Deer/ScriptEngine.h"
#include "imgui.h"

namespace Deer {
	GamePanel::GamePanel() {
		FrameBufferSpecification fbSpecs = FrameBufferSpecification(
		    100, 100, {TextureBufferType::RGBA8}, 1, false);
		m_frameBuffer = Scope<FrameBuffer>(FrameBuffer::create(fbSpecs));
	}

	void GamePanel::onImGui() {
		ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
		ImGui::Begin("Game Window");
		ImGui::PopStyleVar();

		Environment& environment = Scene::environment;
		uint32_t cameraUID = environment.tryGetMainCamera();

		if (cameraUID == 0) {
			ImGui::TextColored(ImVec4(.3f, .3f, .8f, 1.0f),
			                   "There is no camera");

			if (!Scene::getExecutingState()) {
				if (ImGui::Button("Execute")) {
					DataStore::exportRuntimeScene();
					Scene::initExecution();
				}
			} else {
				if (ImGui::Button("Stop")) {
					Scene::endExecution();
					DataStore::importRuntimeScene();
				}
			}

			ImGui::End();
			return;
		}

		Entity& cameraEntity = environment.getEntity(cameraUID);
		CameraComponent& cameraComponent =
		    cameraEntity.getComponent<CameraComponent>();

		ImVec2 contentRegionMin = ImGui::GetWindowContentRegionMin();
		ImVec2 pos = ImGui::GetWindowPos();
		pos.y += contentRegionMin.y;

		ImVec2 windowSize = ImGui::GetContentRegionAvail();
		ImVec2 cursorPos = ImGui::GetCursorPos();

		if (m_lastWindowSize != *(glm::vec2*)&windowSize) {
			m_lastWindowSize = {windowSize.x, windowSize.y};
			m_frameBuffer->resize(windowSize.x, windowSize.y);

			cameraComponent.aspect = windowSize.x / windowSize.y;
		}

		m_frameBuffer->bind();
		m_frameBuffer->clear();
		unsigned char clearColor[4]{0, 0, 0, 255};
		m_frameBuffer->clearBuffer(0, &clearColor);

		Scene::render();
		m_frameBuffer->unbind();

		ImGui::Image((void*)(uint64_t)m_frameBuffer->getTextureBufferID(0),
		             windowSize, ImVec2(0, 1), ImVec2(1, 0));

		ImGui::SetCursorPos(cursorPos);

		if (!Scene::getExecutingState()) {
			if (ImGui::Button("Execute")) {
				DataStore::exportRuntimeScene();
				Scene::initExecution();
			}
		} else {
			if (ImGui::Button("Stop")) {
				Scene::endExecution();
				DataStore::importRuntimeScene();
			}
		}

		ImGui::End();
	}
}  // namespace Deer