#include <vereign/core/string.hh>

#include <iostream>

#ifdef _WIN32
# include <windows.h>
# include <stringapiset.h>
#endif

namespace vereign::string {

#ifdef _WIN32

auto widen(std::string_view utf8_str) -> std::wstring {
  if (utf8_str.empty()) {
    return L"";
  }

  int num_chars = MultiByteToWideChar(CP_UTF8 , 0, utf8_str.data(), utf8_str.length(), nullptr, 0);
  if (num_chars == 0) {
    return std::wstring{};
  }

  std::wstring result;
  result.resize(num_chars);
  num_chars = MultiByteToWideChar(
    CP_UTF8,
    0,
    utf8_str.data(),
    utf8_str.length(),
    result.data(),
    num_chars
  );

  if (num_chars == 0) {
    return L"";
  }

  return result;
}

auto narrow(std::wstring_view utf16_str) -> std::string {
  if (utf16_str.empty()) {
    return "";
  }

  int num_chars = WideCharToMultiByte(
    CP_UTF8,
    0,
    utf16_str.data(),
    utf16_str.length(),
    nullptr,
    0,
    nullptr,
    nullptr
  );

  if (num_chars == 0) {
    return "";
  }

  std::string result;
  result.resize(num_chars);
  num_chars = WideCharToMultiByte(
    CP_UTF8,
    0,
    utf16_str.data(),
    utf16_str.length(),
    result.data(),
    num_chars,
    nullptr,
    nullptr
  );

  if (num_chars == 0) {
    return "";
  }

  return result;
}

#endif

} // vereign::string