#include "WindowsGraphics.h"

#include "Game.h"
#include <iostream>
#include <glad/glad.h>
#include "WindowsInput.h"


void WindowsGraphics::SwapBuffer()
{
	glFlush();
	glfwSwapBuffers(window);
	glfwPollEvents();
}

GLFWwindow& WindowsGraphics::Window() const
{
	return *window;
}
WindowsGraphics::WindowsGraphics()
{
    // Initialize GLFW and set window properties.
    glfwInit();
    glfwWindowHint(GL_DEPTH_BUFFER_BIT, 16);
    glfwWindowHint(GL_DEPTH_BITS, 16);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // should be 2.0 for Pi3, but
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); // we can use 3.1 for ES to do nicer things on PC only

    // ideally we want this, 
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
// if this fails we can use one of these, a few Graphic cards don't like ES. 
//   GLFW_OPENGL_ANY_PROFILE              
//   GLFW_OPENGL_CORE_PROFILE 


    // Creates the window.
    std::string title = std::string("PC Based OpenGLES ") + PROJECT_NAME;
    window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, title.c_str(), NULL, NULL);

    // Error handling for if window creation failed.
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window! check the WindowsGraphics.cpp file" << std::endl;
        glfwTerminate();
    }

    // Set the window to be the current context.
    glfwMakeContextCurrent(window);

    // Error handling  if GLAD failed to initialize.
    if (!gladLoadGLES2Loader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD! check the WindowsGraphics.cpp file" << std::endl;
    }

    // Now position the window on a preferred monitor after GLAD initialization
    // Get all monitors if we have 2 play our content on the 2nd.
    int monitorCount;
    GLFWmonitor** monitors = glfwGetMonitors(&monitorCount);
    int Preffered = 1; // use 0 for main primary, or 1 for 2nd if you have it
// this can make debugging cleaner since you can keep VS on one screen and your project on a 2nd
    GLFWmonitor* targetMonitor;
    if (monitorCount >= 2) {
        targetMonitor = monitors[Preffered]; // Index 1 is the second monitor
    }
    else {
        targetMonitor = glfwGetPrimaryMonitor();
    }

    // Get the screen/monitor resolution of the selected monitor
    const GLFWvidmode* mode = glfwGetVideoMode(targetMonitor);

    // Calculate position to center the window on the selected monitor
    int monitorX, monitorY;
    glfwGetMonitorPos(targetMonitor, &monitorX, &monitorY);

    int xPos = monitorX + (mode->width - WINDOW_WIDTH) / 2;
    int yPos = monitorY + (mode->height - WINDOW_HEIGHT) / 2;

    // Set window position after initialization
    glfwSetWindowPos(window, xPos, yPos);
}

void WindowsGraphics::Quit()
{
	glfwDestroyWindow(window);
}
