#include "adapters/windows/fonts/WindowsFontLocator.h"

#include <Windows.h>

#include <filesystem>

namespace ta::adapters::windows::fonts
{
    namespace
    {
        std::optional<std::string> wide_to_utf8(const std::wstring& value) noexcept
        {
            if (value.empty())
                return std::nullopt;
            const int size = WideCharToMultiByte(
                CP_UTF8, WC_ERR_INVALID_CHARS, value.c_str(), static_cast<int>(value.size()),
                nullptr, 0, nullptr, nullptr);
            if (size <= 0)
                return std::nullopt;
            std::string result(static_cast<std::size_t>(size), '\0');
            if (WideCharToMultiByte(
                    CP_UTF8, WC_ERR_INVALID_CHARS, value.c_str(), static_cast<int>(value.size()),
                    result.data(), size, nullptr, nullptr) <= 0)
                return std::nullopt;
            return result;
        }
    }

    std::optional<std::string> find_system_font(const std::wstring_view file_name) noexcept
    {
        if (file_name.empty())
            return std::nullopt;

        wchar_t windows_directory[MAX_PATH] = {};
        if (!GetWindowsDirectoryW(windows_directory, MAX_PATH))
            return std::nullopt;

        const std::filesystem::path path =
            std::filesystem::path(windows_directory) / L"Fonts" / file_name;
        std::error_code ec;
        if (!std::filesystem::is_regular_file(path, ec) || ec)
            return std::nullopt;
        return wide_to_utf8(path.wstring());
    }
}
