/*Copyright (C) 2010-2023 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Hikou no mizu is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "Timer.hpp"

#include <thread>

Timer::Timer() : m_previousTime(getTime())
{

}

void Timer::reset()
{
    m_previousTime = getTime();
}

void Timer::resetToElapsed(const duration_uint64_us &duration)
{
    m_previousTime = getTime() - duration;
}

void Timer::waitUntilElapsed(const duration_float_ms &duration) const
{
    duration_float_ms elapsed = getTime() - m_previousTime;

    if (duration > elapsed)
        Timer::sleep(duration - elapsed);
}

float Timer::getElapsed() const
{
    return duration_float_ms(getTime() - m_previousTime).count();
}

Timer::duration_uint64_us Timer::getTicks(const TimePoint &now) const
{
    return std::chrono::duration_cast<duration_uint64_us>(
        now - m_previousTime);
}

//Static methods
void Timer::sleep(const duration_float_ms &duration)
{
    std::this_thread::sleep_for(duration);
}

Timer::TimePoint Timer::getTime()
{
    return std::chrono::steady_clock::now();
}
