#include <iostream>
#include <glad/gl.h>
#include <GLFW/glfw3.h>
#include <glm/vec3.hpp> // glm::vec3
#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <pugixml.hpp>
#include "utils/logger.h"
#include "utils/op_res.h"
#include "core/state.h"
#include "core/version.h"
#include "utils/args.h"

extern "C"
{
	#include <lua.h>
	#include <lauxlib.h>
	#include <lualib.h>
}

//#include <windows.h>

// the following can also be <LunariumConfig.h> but it results in 
// an intellisense error
#include "../build/LunariumConfig.h"

int main(int argc, char** argv)
{
    // char pBuf[256];
    // size_t len = sizeof(pBuf); 
    // int bytes = GetModuleFileNameA(NULL, pBuf, len);
    // std::cout <<pBuf << std::endl;

    // VERSION TEST
    std::cout << "Hello yall\n";
    std::cout << "This is " << argv[0] << " Version " << lunarium::Version::GetVersion().ToString() << "\n";

    glm::vec3 testVec = glm::vec3(1.0f, 2.0f, 3.0f);

    std::cout << "\ntestVec: (" << testVec.x << ", " << testVec.y << ", " << testVec.z << ")\n";

    // Args testing
    std::vector<lunarium::Args::SwitchDesc> sd;
    sd.push_back({ "t", true});
    sd.push_back({ "d", true});
    sd.push_back({ "h", false});
    lunarium::Args args(argc, argv, '-', sd);

    if (args.ContainsSwitch("t"))
    {
        std::cout << "t switch is: " << args.GetSwitchValue("t") << "\n";
    }

    if (args.ContainsSwitch("d"))
    {
        std::cout << "d switch is: " << args.GetSwitchValue("d") << "\n";
    }

    if (args.ContainsSwitch("h"))
    {
        std::cout << "h switch is found!\n";
    }

    if (args.GetNumPositionalArgs() > 1)
    {
        std::cout << "First position argument: " << args.GetArgAtPosition(1) << std::endl;
    }

    // LUA TEST
    std::cout << "\nTesting LUA: a = 7 + 4\n";
    lua_State* L = luaL_newstate();
    std::string cmd = "a = 7 + 4";
    int r = luaL_dostring(L, cmd.c_str());

	if (r == LUA_OK)
	{
		lua_getglobal(L, "a");
		if (lua_isnumber(L, -1))
		{
			float a_in_cpp = (float)lua_tonumber(L, -1);
			std::cout << "a is: " << a_in_cpp << std::endl;
		}
	}
	else
	{
		std::string errormsg = lua_tostring(L, -1);
		std::cout << errormsg << std::endl;
	}
    lua_close(L);

    // PUGIXML TEST
    std::cout << "\nAttempting to open test.xml...";
    pugi::xml_document doc;
    pugi::xml_parse_result result = doc.load_file("test_data/test.xml");
    if (!result)
    {
        std::cout << "\nCould not open the file!\n";
        return -1;
    }
    else
    {
        int x = doc.child("test").attribute("x").as_int();
        std::cout << "\nPugiXML worked! -- x is: " << x << std::endl;
    }
    std::cout <<"\nTesting loading the default state...";
    lunarium::State ds = lunarium::State::CreateDefault();

    std::cout <<"\nTesting loading a state from file...";
    lunarium::State testState;
    if (lunarium::IsOK(lunarium::State::CreateFromFile("lunarium_state.xml", testState)))
    {
        std::cout << "\nIt worked! Full Screen Resolution Width: " << testState.Display.FullScreenResolution.Width;
        std::cout << "\nSaving out to test_save.xml";

        if (lunarium::IsOK(testState.SaveToFile("test_save.xml")))
        {
            std::cout << "\nSuccess!\n";
        }
        else
        {
            std::cout << "\nFailed to save the file...\n";
        }
    }

    std::cout << "\nTesting GLFW and ImGui\n";

    // GLFW DEAR IMGUI TEST
    GLFWwindow* window;
    int width, height;

    if( !glfwInit() )
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        exit( EXIT_FAILURE );
    }

    glfwWindowHint(GLFW_DEPTH_BITS, 16);
    glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);    
    
     // GL 4.5 + GLSL 330
    const char* glsl_version = "#version 450";
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);

    window = glfwCreateWindow( 1280, 720, "Lunarium", NULL, NULL );
    if (!window)
    {
        fprintf( stderr, "Failed to open GLFW window\n" );
        glfwTerminate();
        exit( EXIT_FAILURE );
    }

    glfwMakeContextCurrent(window);
    glfwSwapInterval(1); // Enable vsync

    // Use glad2 to load extensions
    int version = gladLoadGL(glfwGetProcAddress);
    printf("GL %d.%d\n", GLAD_VERSION_MAJOR(version), GLAD_VERSION_MINOR(version));

    int testwidth = 0;
    int testheight = 0;
    glfwGetFramebufferSize(window, &testwidth, &testheight);
    std::cout << "\nframe buffer size: " << testwidth << ", " << testheight << "\n";

     // Setup Dear ImGui context
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;       // Enable Keyboard Controls
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls
    io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;           // Enable Docking
    io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;         // Enable Multi-Viewport / Platform Windows
    //io.ConfigViewportsNoAutoMerge = true;
    //io.ConfigViewportsNoTaskBarIcon = true;

    // Setup Dear ImGui style
    ImGui::StyleColorsDark();
    //ImGui::StyleColorsClassic();

    // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
    ImGuiStyle& style = ImGui::GetStyle();
    if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
    {
        style.WindowRounding = 0.0f;
        style.Colors[ImGuiCol_WindowBg].w = 1.0f;
    }

    // Setup Platform/Renderer backends
    ImGui_ImplGlfw_InitForOpenGL(window, true);
    ImGui_ImplOpenGL3_Init(glsl_version);

      // Our state
    bool show_demo_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);


    // Main loop
    while( !glfwWindowShouldClose(window) )
    {
          // Poll and handle events (inputs, window resize, etc.)
        // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
        // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
        // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
        // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
        glfwPollEvents();

        // Start the Dear ImGui frame
        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();

        // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
        if (show_demo_window)
            ImGui::ShowDemoWindow(&show_demo_window);


        // Rendering
        ImGui::Render();
        int display_w, display_h;
        glfwGetFramebufferSize(window, &display_w, &display_h);
        glViewport(0, 0, display_w, display_h);
        glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
    	
        // Update and Render additional Platform Windows
        // (Platform functions may change the current OpenGL context, so we save/restore it to make it easier to paste this code elsewhere.
        //  For this specific demo app we could also call glfwMakeContextCurrent(window) directly)
        if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
        {
          //  GLFWwindow* backup_current_context = glfwGetCurrentContext();
            ImGui::UpdatePlatformWindows();
            ImGui::RenderPlatformWindowsDefault();
            //glfwMakeContextCurrent(backup_current_context);
        }

        glfwSwapBuffers(window);
    }

      // Cleanup
    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplGlfw_Shutdown();
    ImGui::DestroyContext();

    glfwDestroyWindow(window);
    glfwTerminate();

    return 0;
}