#include <glad/glad.h>
#include <GLFW/glfw3.h>

#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <iostream>

int main(int argc, char **argv) {
	std::cout << "Hello working!" << std::endl;


	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	//glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	// make the window
	GLFWwindow *window = glfwCreateWindow(640, 480, "OpenGL Demo", NULL, NULL);
	if (!window) {

		std::cout << "Failed to create GLFW window." << std::endl;
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent(window);
	// d

	// load graphics
	if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
		std::cerr << "Failed to initialize OpenGL loader!" << std::endl;
		return -1;
	}
	glViewport(0, 0, 640, 480);
	// d

	// now make ImGui
	IMGUI_CHECKVERSION();
	ImGui::CreateContext();
	ImGuiIO &io = ImGui::GetIO();
	(void)io;
	io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
	ImGui::StyleColorsDark();
	ImGui_ImplGlfw_InitForOpenGL(window, true);
	ImGui_ImplOpenGL3_Init("#version 130");
	/// im a dumbass
	///

	// program
	while (!glfwWindowShouldClose(window)) {
		static bool dragging_window = false;
		static double drag_start_mouse_x, drag_start_mouse_y;
		static int drag_start_window_x,drag_start_window_y;

		glClearColor(1.0f, .5f, .2f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		glfwPollEvents();

		ImGui_ImplOpenGL3_NewFrame();
		ImGui_ImplGlfw_NewFrame();
		ImGui::NewFrame();

		ImGui::BeginMainMenuBar();

		if (ImGui::IsItemHovered() && ImGui::IsMouseClicked(0)) {
			dragging_window = true;


			glfwGetCursorPos(window, &drag_start_mouse_x, &drag_start_mouse_y);

			// Get  window pos
			glfwGetWindowPos(window, &drag_start_window_x, &drag_start_window_y);
		}

		if (dragging_window && ImGui::IsMouseDown(0)) {
			double current_mouse_x, current_mouse_y;
			glfwGetCursorPos(window, &current_mouse_x, &current_mouse_y);


			double dx = current_mouse_x - drag_start_mouse_x;
			double dy = current_mouse_y - drag_start_mouse_y;

			// Move window
			glfwSetWindowPos(window,
				drag_start_window_x + static_cast<int>(dx),
				drag_start_window_y + static_cast<int>(dy));
		} else {
			dragging_window = false;
		}

		// Menu items
		if (ImGui::BeginMenu("File")) {
			if (ImGui::MenuItem("Exit")) {
				glfwSetWindowShouldClose(window, true);
			}
			ImGui::EndMenu();
		}
		ImGui::EndMainMenuBar();

		ImGui::Begin("Editor");
		ImGui::Text("Hello from editor");
		ImGui::End();

		ImGui::Render();
		ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
		glfwSwapBuffers(window);
	}

	glfwDestroyWindow(window);
	glfwTerminate();

	return 0;
}
