#include <init.hpp>
#include <glad/glad.h>
//#include <SDL2/SDL.h>
#include <SDL.h>
#include <string>
#include <iostream>
#include <infrastructure.hpp>

bool Infrastructure::init(const std::string name, const int width, const int height)
{
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        std::cerr << "SDL2 video subsystem couldn't be initialized. Error: "
            << SDL_GetError()
            << std::endl;
        return false;
    }

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);

    //MSAA
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);

    window_ = SDL_CreateWindow(name.c_str(), SDL_WINDOWPOS_CENTERED /*SDL_WINDOWPOS_CENTERED_DISPLAY(1)*/, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_FULLSCREEN);
    //uncomment to make ginormous windows visible
    //SDL_SetWindowPosition(window, 0, 0);

    context_ = SDL_GL_CreateContext(window_);

    renderer_ = /*nullptr;*/SDL_CreateRenderer(window_, -1, SDL_RENDERER_ACCELERATED);

    if (renderer_ == nullptr) {
        std::cerr << "SDL2 Renderer couldn't be created. Error: "
            << SDL_GetError()
            << std::endl;
        return false;
    }



    SDL_GL_MakeCurrent(window_, context_); //WINDOWS throws error in imgui without this



    //glad
    if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) {
        std::cerr << "Failed to initialize the OpenGL context." << std::endl;
        return false;
    }

    std::cout << "OpenGL version loaded: " << GLVersion.major << "." << GLVersion.minor << std::endl;

    glViewport(0, 0, width, height);
    glClearColor(0.0f, 0.0f, 0.0f, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);
    SDL_GL_SetSwapInterval(1); //1 to turn on VSync, 0 to turn off VSync

    return true;
}