#include <maps/wikimap/mapspro/services/mrc/libs/common/include/stopwatch.h>

#include <maps/libs/common/include/exception.h>

namespace maps::mrc::common {

Stopwatch::Stopwatch(State state) : state_{state}
{
    reset();
}

void Stopwatch::start()
{
    REQUIRE(state_ == Stopped, "Stopwatch is already started");
    state_ = Running;
    start_ = Clock::now();
}

void Stopwatch::stop()
{
    REQUIRE(state_ == Running, "Stopwatch is already stopped");
    state_ = Stopped;
    elapsed_ += Clock::now() - start_;
}

void Stopwatch::reset()
{
    start_ = Clock::now();
    elapsed_ = Duration::zero();
}


IntervalsTimer::IntervalsTimer(std::string name)
    : name_(std::move(name))
    , currentIntervalStart_()
{
    start_ = Clock::now();
    currentIntervalStart_ = start_;
}

IntervalsTimer& IntervalsTimer::endInterval(std::string interval)
{
    auto curTime = Clock::now();
    splits_.push_back(Split{.name = std::move(interval),
        .duration = curTime - currentIntervalStart_});
    currentIntervalStart_ = curTime;
    return *this;
}

} // namespace maps::mrc::common
