#include "EngineConfig.h"
#include <yaml-cpp/yaml.h>
#include <filesystem>
#include <fstream>
#include <Windows.h>
#include <shlobj.h>

#include "Logging.h"



//! Macro Fuckery my Gz

EngineConfig g_engineConfig{
    .version = "0.1.0",
    .gl_version = "430",
    .gl_maxLight = 512,
    .settings = UserSettings{}
};

static std::filesystem::path GetUserSettingsPath()
{
    char userPath[MAX_PATH];
    if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_PROFILE, NULL, 0, userPath)))
    {
        std::filesystem::path path = std::filesystem::path(userPath) / ".CreateEngine" / ".user_settings.yaml";
        std::filesystem::create_directories(path.parent_path());
        Logger::LogVerbose("Settings Path: %s", path.string().c_str());
        return path;
    }
    return {};
}

void EngineConfig::SaveToFile()
{
    Logger::LogVerbose("Saving User Settings");

    YAML::Emitter out;
    out << YAML::BeginMap;

    out << YAML::Key << "settings" << YAML::Value;
    out << YAML::BeginMap;

#define USER_SETTING(name, type, default_val) out << YAML::Key << #name << YAML::Value << settings.name;
    USER_SETTINGS_TABLE
#undef USER_SETTING

    out << YAML::EndMap;

    out << YAML::EndMap;

    std::ofstream fout(GetUserSettingsPath());
    fout << out.c_str();
}

void EngineConfig::LoadFromFile()
{
    Logger::LogVerbose("Loading User Settings");

    auto path = GetUserSettingsPath();
    if (!std::filesystem::exists(path))
        return;

    YAML::Node root = YAML::LoadFile(path.string());
    YAML::Node section = root["settings"];
    if (!section)
        return;

#define USER_SETTING(name, type, default_val) \
    if (section[#name]) settings.name = section[#name].as<type>();
    USER_SETTINGS_TABLE
#undef USER_SETTING
}

