#include <cerrno>
#include <cstring>

#include <ThreadClock/ThreadClock.hpp>
#include <Utilities/Utilities.hpp>

using namespace std::chrono_literals;

void ThreadClock::reset()
{
#ifndef _WIN32
    if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &startTime) != 0)
    {
        crash(formatString("ThreadClock::reset: clock_gettime: $+", strerror(errno)));
    }
#endif
}

ThreadClock::Duration ThreadClock::getDuration()
{
#ifdef _WIN32
    return Duration(0);
#else
    struct timespec current;
    if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &current) != 0)
    {
        crash(formatString("ThreadClock::getDuration: clock_gettime: $+", strerror(errno)));
    }

    time_t diffSecs = current.tv_sec - startTime.tv_sec;
    long diffNS = current.tv_nsec - startTime.tv_nsec;

    return diffSecs * 1s + diffNS * 1ns;
#endif
}