#include "time.hpp"

#include <chrono>
#include <format>
#include <iomanip>
#include <sstream>

namespace game::util::time
{
  constexpr auto ROUNDING_DIVISOR = 2;

  std::string get(const char* format)
  {
    auto now = std::chrono::system_clock::now();
    auto nowTime = std::chrono::system_clock::to_time_t(now);
    std::tm localTime{};
#ifdef _WIN32
    localtime_s(&localTime, &nowTime);
#else
    localtime_r(&nowTime, &localTime);
#endif
    std::ostringstream timeString;
    timeString << std::put_time(&localTime, format);
    return timeString.str();
  }

  std::string ticks_to_minutes_seconds(int ticks, int ticksPerSecond)
  {
    auto seconds = ticksPerSecond <= 0 ? 0 : ticks / ticksPerSecond;
    auto minutes = seconds / SECOND_M;
    seconds %= SECOND_M;
    return std::format("{}:{:02}", minutes, seconds);
  }

  std::string ticks_to_minutes_seconds_centiseconds(int ticks, int ticksPerSecond)
  {
    ticks = ticks < 0 ? 0 : ticks;
    if (ticksPerSecond <= 0) return "0'00\"00";
    auto totalCentiseconds = ((ticks * CENTISECONDS_PER_SECOND) + (ticksPerSecond / ROUNDING_DIVISOR)) / ticksPerSecond;
    auto minutes = totalCentiseconds / (SECOND_M * CENTISECONDS_PER_SECOND);
    auto seconds = (totalCentiseconds / CENTISECONDS_PER_SECOND) % SECOND_M;
    auto centiseconds = totalCentiseconds % CENTISECONDS_PER_SECOND;
    return std::format("{}'{:02}\"{:02}", minutes, seconds, centiseconds);
  }
}
