//
//  timeController.cpp
//  tweakathlon
//
//  Created by Robert Tubb on 10/02/2014.
//
//

#include "timeController.h"

TimeController timeController;


//----------------
void TimeController::callAndEraseAllExpired(TimerMicrosec timeNow){
    
    for(auto iter = timesAndCalls.begin(); iter != timesAndCalls.end(); ) {
        if ( (*iter).first < timeNow) {
            (*iter).second();
            timesAndCalls.erase(iter++);
        } else {
            ++iter;
        }
    }
};

//----------------
void TimeController::cancelEvent(TimerID which){
    //
    for(auto it = timesAndCalls.begin(); it != timesAndCalls.end();){
        if ((*it).first == which) {
            timesAndCalls.erase(it++);
        } else {
            ++it;
        }
    }
    
};
//----------------
TimerID TimeController::scheduleEvent(TimerCallbackFunction cbfunc, int howLongMillisec){
    
    TimerID fireTime = TimerID(getMicrosecTimeNow()+ 1000.0*howLongMillisec);
    timesAndCalls.insert( TimeAndCallPair(fireTime, cbfunc));
    
    
    return fireTime;
};

//----------------
void TimeController::startStopwatch(){
    if (stopWatchRunning){
        cout << "ERROR stop watch already running" << endl;
    }
    
    stopWatchStartTime = TimerMillisec(getMicrosecTimeNow()/1000);
    stopWatchRunning = true;
}
//----------------
TimerMillisec TimeController::stopStopwatch(){
    if (!stopWatchRunning) return 0;
    stopWatchRunning = false;
    TimerMillisec elapsedTime = getMicrosecTimeNow()/1000 - stopWatchStartTime;
    stopWatchStartTime = 0;
    return elapsedTime;
}
//----------------
TimerMillisec TimeController::getStopwatchElapsedTime(){
    if (!stopWatchRunning) return 0;
    TimerMillisec elapsedTime = getMicrosecTimeNow()/1000  - stopWatchStartTime;
    return elapsedTime;
}
//----------------