#include <GLFW/glfw3.h>
#include <ctime>
#include <cstdlib>
#include "log.h"
#include "window.h"
#include <input.h>
#include <config.h>
#include <render/render.h>
#include "color.h"
#include "resources.h"
#include "game/game.h"
#include "imgui/imgui.h"
#include "imgui/imgui_impl_glfw_gl3.h"

void init();
void close();

void _glfwError(int, const char*);

int main()
{
    init();
    game::init();

    ImGui_ImplGlfwGL3_Init(window::getHandler(), false);

    ImGui::GetIO().Fonts->AddFontFromFileTTF("data/fonts/Roboto-Regular.ttf", 14, NULL, ImGui::GetIO().Fonts->GetGlyphRangesCyrillic());

    render::setClearColor(color::uint2rgba(0x333333));
    render::mode2D();

    while(!window::shouldClose())
    {
        ImGui_ImplGlfwGL3_NewFrame(input::getScroll());

        game::update();

        render::setClearColor(color::uint2rgba(0x333333));
        render::clearScreen();

        game::draw();

        render::flush();
        ImGui::Render();
        window::swapBuffers();
        window::pollEvents();
    }

    game::free();
    ImGui_ImplGlfwGL3_Shutdown();
    close();
}


void init()
{
    _log::init();
    config::init();
    srand(time(0));
    glfwSetErrorCallback(_glfwError);
    glfwInit();
    _log::out("GLFW %s\n", glfwGetVersionString());
    window::initMonitors();
    window::createWindow(config::window::size, u8"Химзавод");
    window::setSizeBounds(vec2i(800, 600), vec2i(-1));

    if(config::window::monitor >= 0)
        window::monitors[config::window::monitor].bind();

    render::init();

    resources::init();
}

void close()
{

    render::free();
    window::closeWindow();
    glfwTerminate();
    _log::close();
    exit(0);
}

void _glfwError(int type, const char* error)
{
    _log::out("GLFW => %s\n", error);
    switch(type)
    {
    case GLFW_NO_CURRENT_CONTEXT:
    case GLFW_OUT_OF_MEMORY:
    case GLFW_API_UNAVAILABLE:
    case GLFW_VERSION_UNAVAILABLE:
    case GLFW_PLATFORM_ERROR:
        _log::out("FATAL ERROR; ");
        _log::close();
        abort();
        break;
    }
}

