#include "OS-ImGui_Base.h"
#include "imgui/imgui_impl_win32.h"
#include "imgui/imgui_impl_dx11.h"

namespace RenderCore
{
    bool OSImGui_Base::InitImGui(ID3D11Device* device, ID3D11DeviceContext* device_context)
    {
        ImGui::CreateContext();
        ImGuiIO& io = ImGui::GetIO();
        
        // 获取 DPI 缩放比例
        float dpiScale = ImGui_ImplWin32_GetDpiScaleForHwnd(Window.hWnd);
        if (dpiScale <= 0.0f) dpiScale = 1.0f;

        ImFontAtlas* fontAtlas = new ImFontAtlas();
        ImFontConfig arialConfig;
        arialConfig.FontDataOwnedByAtlas = false;
        
        // 缩放字体大小
        fontAtlas->AddFontFromFileTTF("c:\\Windows\\Fonts\\msyh.ttc", 15.0f * dpiScale, &arialConfig, io.Fonts->GetGlyphRangesAll());
        fontAtlas->AddFontFromFileTTF("c:\\Windows\\Fonts\\msyh.ttc", 20.0f * dpiScale, &arialConfig, io.Fonts->GetGlyphRangesAll());
        fontAtlas->AddFontFromFileTTF("c:\\Windows\\Fonts\\msyh.ttc", 18.0f * dpiScale, &arialConfig, io.Fonts->GetGlyphRangesAll());
        
        io.Fonts = fontAtlas;

        // 缩放 UI 样式
        ImGui::AimStarDefaultStyle();
        ImGui::GetStyle().ScaleAllSizes(dpiScale);
        
        io.LogFilename = nullptr;

        if (!ImGui_ImplWin32_Init(Window.hWnd))
            throw OSException("ImGui_ImplWin32_Init() call failed.");
        if (!ImGui_ImplDX11_Init(device, device_context))
            throw OSException("ImGui_ImplDX11_Init() call failed.");

        return true;
    }

    void OSImGui_Base::CleanImGui()
    {
        ImGui_ImplDX11_Shutdown();
        ImGui_ImplWin32_Shutdown();
        ImGui::DestroyContext();

        g_Device.CleanupDeviceD3D();
        DestroyWindow(Window.hWnd);
        UnregisterClassA(Window.ClassName.c_str(), Window.hInstance);
    }

    std::wstring OSImGui_Base::StringToWstring(std::string& str)
    {
        std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
        return converter.from_bytes(str);
    }
}