/*
 * Copyright (C) 2015 by Multi-Tech Systems
 *
 * This file is part of libmts.
 *
 * libmts is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * libmts 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with libmts.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <mts/MTS_Timer.h>
#include <mts/MTS_System.h>

using namespace MTS;

Timer::Timer()
: m_iStart(0)
, m_iPause(0)
, m_bStarted(false)
, m_bPaused(false)
{

}

Timer::~Timer() {

}

void Timer::start() {
    if(m_bStarted) {
        return;
    }

    m_iStart = System::timeMicros();
    m_bStarted = true;
    m_bPaused = false;
}

void Timer::stop() {
    m_bStarted = false;
}

void Timer::pause() {
    if(m_bPaused || !m_bStarted) {
        return;
    }

    m_iPause = System::timeMicros();
    m_bPaused = true;
}

void Timer::resume() {
    if(!m_bPaused) {
        return;
    }

    m_iStart += System::timeMicros() + m_iPause;
    m_bPaused = false;
}

void Timer::reset() {
    m_iStart = System::timeMicros();
    m_bPaused = false;
}

bool Timer::isRunning() {
    return !m_bPaused && m_bStarted;
}

uint64_t Timer::getMicros() {
    if(!m_bStarted) {
        return 0;
    }

    if(m_bPaused) {
        return m_iPause - m_iStart;
    }

    return System::timeMicros() - m_iStart;
}

uint64_t Timer::getMillis() {
    return getMicros() / 1000;
}

uint64_t Timer::getSeconds() {
    return getMicros() / 1000000;
}

uint64_t Timer::getMinutes() {
    return getMicros() / (1000000*60);
}