#include "states_render.h"

#include <Windows.h>
#include <filesystem>

namespace {
std::filesystem::path tempPath_defaultShader{L"I:/source/render/assets/shaders/_this_is_fuckin_default_shader.hlsl"};
std::filesystem::path tempPath_defaultPBRShader{L"I:/source/render/assets/shaders/pbr_forward.hlsl"};
std::filesystem::path tempPath_shadowDepth{L"I:/source/render/assets/shaders/shadow_depth_vs.hlsl"};
std::filesystem::path tempPath_PbrWithIbl{L"I:/source/render/assets/shaders/pbr_forward_ibl.hlsl"};

}

const std::wstring &StatesRender::S_GetExeDir() {
    static const std::wstring dir = []() -> std::wstring {
        std::wstring buffer(MAX_PATH, L'\0');
        for (;;) {
            const DWORD length = GetModuleFileNameW(
                nullptr,
                buffer.data(),
                static_cast<DWORD>(buffer.size())
            );

            if (length == 0) {
                throw std::system_error(
                    static_cast<int>(GetLastError()),
                    std::system_category(),
                    "GetModuleFileNameW failed"
                );
            }

            if (length < buffer.size()) {
                buffer.resize(length);
                const std::filesystem::path filePath(buffer);
                return filePath.parent_path().wstring();
            }

            // 缓冲区不足，扩大后重试
            buffer.resize(buffer.size() * 2);
        }
    }();

    return dir;
}

const std::filesystem::path &StatesRender::S_GetDefaultShaderPath() {
    // DEBUG MODE
    return tempPath_PbrWithIbl;
    return tempPath_defaultPBRShader;
    return tempPath_defaultShader;

    // 正确的
    static std::filesystem::path shaderpath = []()-> std::filesystem::path {
        std::filesystem::path rootdir{S_GetExeDir()};
        std::filesystem::path _shaderpath = rootdir / L"assets/shaders/_this_is_fuckin_default_shader.hlsl";
        if (!std::filesystem::exists(_shaderpath)) {
            MessageBoxW(nullptr, L"exe目录下找不到assets/shaders/_default_shader.hlsl", L"StatesRender.cpp",MB_OK);
            throw std::runtime_error{"default shader does not exist"};
        }
        return _shaderpath;
    }();

    return shaderpath;
}

const std::filesystem::path &StatesRender::S_GetShadowDepthShaderPath() {

    // DEBUG MODE
    return tempPath_shadowDepth;


    // 正确的
    static std::filesystem::path shaderpath = []()-> std::filesystem::path {
        std::filesystem::path rootdir{S_GetExeDir()};
        std::filesystem::path _shaderpath = rootdir / L"assets/shaders/shadow_depth_vs.hlsl";
        if (!std::filesystem::exists(_shaderpath)) {
            MessageBoxW(nullptr, L"exe目录下找不到assets/shaders/shadow_depth_vs.hlsl", L"StatesRender.cpp",MB_OK);
            throw std::runtime_error{"default shader does not exist"};
        }
        return _shaderpath;
    }();

    return shaderpath;
}












//
