#include "RuntimeClock.h"

#include <chrono>

namespace
{
bool ToUtcTime(std::time_t time, std::tm& utcTime)
{
	return gmtime_s(&utcTime, &time) == 0;
}

bool ToLocalTime(std::time_t time, std::tm& localTime)
{
	return localtime_s(&localTime, &time) == 0;
}
}

RuntimeClockSnapshot GetRuntimeClockSnapshot()
{
	return MakeRuntimeClockSnapshot(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()));
}

RuntimeClockSnapshot MakeRuntimeClockSnapshot(std::time_t now)
{
	RuntimeClockSnapshot snapshot;

	std::tm utcTime = {};
	if (!ToUtcTime(now, utcTime))
		return snapshot;

	snapshot.utcTimeSeconds =
		static_cast<double>(utcTime.tm_hour * 3600 + utcTime.tm_min * 60 + utcTime.tm_sec);

	std::tm localTime = {};
	if (!ToLocalTime(now, localTime))
		return snapshot;

	utcTime.tm_isdst = localTime.tm_isdst;
	const std::time_t localAsTime = std::mktime(&localTime);
	const std::time_t utcAsLocalTime = std::mktime(&utcTime);
	if (localAsTime != static_cast<std::time_t>(-1) && utcAsLocalTime != static_cast<std::time_t>(-1))
		snapshot.utcOffsetSeconds = std::difftime(localAsTime, utcAsLocalTime);

	return snapshot;
}
