#include "DarkRP2D.h"

#ifndef NDEBUG
#include "imgui.h"
#include "imgui_impl_sdl_gl3.h"
#endif

#include <GL/glew.h>
#include <iostream>
#include "screens/GameScreen.h"
#include "Utility.h"

DarkRP2D::~DarkRP2D()
{
	std::cout << "Game got destroyed!" << std::endl;
#ifndef NDEBUG
	ImGui_ImplSdlGL3_Shutdown();
	ImGui::DestroyContext();
#endif
	delete gameScreen;
	delete assets;
	delete renderer;
}

void DarkRP2D::create()
{
	std::cout << "Game got created!" << std::endl;
	assets = new Assets();
	assets->loadTexture("assets/police_officer.png", true, "police_officer");
	assets->loadShader("shaders/vert.shader", "shaders/frag.shader", nullptr, "defaultShader");
	assets->loadShader("shaders/bitmapvert.shader", "shaders/bitmapfrag.shader", nullptr, "bitmapShader");

	renderer = new Renderer();

	font = new BitmapFont("fonts/arial.ttf");

	gameScreen = new GameScreen(renderer, assets);
	gameScreen->show();

#ifndef NDEBUG
	//Setup IMGUI debugging
	ImGui::CreateContext();
	ImGui_ImplSdlGL3_Init(this->gWindow);
	ImGui::StyleColorsDark();
#endif
}

void DarkRP2D::loop(unsigned int delta)
{
	static unsigned int accumulator = 0, ups = 0, fps = 0, acc = 0;
	accumulator += delta;
	acc += delta;

	while (accumulator >= 17)
	{
		accumulator -= 17;
		update(delta);
		ups++;
	}

	if (acc >= 1000)
	{
		std::cout << "Updates per second: " << ups << " Frames per Second: " << fps << std::endl;
		acc -= 1000;
		ups = 0;
		fps = 0;
	}
	render(delta);
	fps++;
}

void DarkRP2D::update(unsigned int delta)
{
	gameScreen->update(delta);
}

void DarkRP2D::render(unsigned int delta)
{
	renderer->clear();
#ifndef NDEBUG
	ImGui_ImplSdlGL3_NewFrame(gWindow);
#endif

	//texttest
	Shader bitmapShader = assets->getShader("bitmapShader");
	font->drawText(bitmapShader, "Hallo du noob", 25.0f, 25.0f, 1.f, glm::vec3(0.5f, 0.8f, 0.2f));

	gameScreen->render(delta);

#ifndef NDEBUG
	// 1. Show a simple window.
	// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
	static bool ShowOpenGLLogger = false;
	{
		ImGui::Separator();
		ImGui::Text("\t\t\t\t\tOpenGL Info");
		ImGui::Text("GLEW Version: %s\n", glewGetString(GLEW_VERSION));
		ImGui::Text("     Version: %s\n", glGetString(GL_VERSION));
		ImGui::Text("      Vendor: %s\n", glGetString(GL_VENDOR));
		ImGui::Text("    Renderer: %s\n", glGetString(GL_RENDERER));
		ImGui::Text("     Shading: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
		ImGui::Separator();
		ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
		ImGui::Checkbox("Show OpenGL Logger", &ShowOpenGLLogger);
	}
	if (ShowOpenGLLogger)
		Utility::Debug::openGLLogger.Draw("OpenGL Logger");

	ImGui::Render();
	ImGui_ImplSdlGL3_RenderDrawData(ImGui::GetDrawData());
#endif

	SDL_GL_SwapWindow(gWindow);
}

void DarkRP2D::resize(int width, int height)
{
}