/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK 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 version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/


#include "Chrono.h"


extern "C" {
#include <ctime>      //
#include <sys/timeb.h> // ftime (chrono)
// #include <time.h> // gettimeofday (chrono)
#if !defined(_WIN32) || defined(__MINGW32__)
#include <sys/time.h> // gettimeofday (chrono)
#include <unistd.h>
#else // MSVC only
    /*int*/ // why this int here?
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <time.h>

#if defined(_MSC_VER) || defined(__BORLANDC__)
#define EPOCHFILETIME (116444736000000000i64)
#else
#define EPOCHFILETIME (116444736000000000LL)
#endif

    struct timezone {
        int tz_minuteswest; /* minutes W of Greenwich */
        int tz_dsttime;     /* type of dst correction */
    };

    __inline int gettimeofday(struct timeval* tv, struct timezone* tz) {
        FILETIME        ft;
        LARGE_INTEGER   li;
        __int64         t;
        static int      tzflag;

        if (tv) {
            GetSystemTimeAsFileTime(&ft);
            li.LowPart  = ft.dwLowDateTime;
            li.HighPart = ft.dwHighDateTime;
            t  = li.QuadPart;       /* In 100-nanosecond intervals */
            t -= EPOCHFILETIME;     /* Offset to the Epoch time */
            t /= 10;                /* In microseconds */
            tv->tv_sec  = (long)(t / 1000000);
            tv->tv_usec = (long)(t % 1000000);
        }

        if (tz) {
            if (!tzflag) {
                _tzset();
                tzflag++;
            }
            tz->tz_minuteswest = _timezone / 60;
            tz->tz_dsttime = _daylight;
        }

        return 0;
    }

#endif
}



// constructor/destructor  Chrono();
Chrono::Chrono() {
    startValue = 0.0;
    stopValue = 0.0;
    accumulatedTime = 0.0;
    running = false;
}

Chrono::Chrono(double init) {
    startValue = init;
    stopValue = init;
    accumulatedTime = 0.0;
    running = false;
}

// start/stop Chrono
void Chrono::start() {
    stopValue = startValue = getTimeInMilliseconds();
    running = true;
    accumulatedTime = 0.0;
}

void Chrono::start(double init) {
    start();
    startValue += init;
    stopValue = startValue;
    running = true;
}

double Chrono::stop() {
    stopValue = getTimeInMilliseconds();
    running = false;
    return (accumulatedTime + stopValue - startValue);
}

void Chrono::hold(bool pause) {
    if (pause) {
        accumulatedTime = stop();
    }
    else {
        double aTime = accumulatedTime;
        start();
        accumulatedTime = aTime;
    }
}

// reset, restart...
void Chrono::reset() {
    startValue = stopValue = accumulatedTime = 0.0;
    running = false;
}

// Get value (without stopping)
double Chrono::get() const {
    if (running) {
        return (accumulatedTime + getTimeInMilliseconds() - startValue);
    }
    else {
        return (accumulatedTime + stopValue - startValue);
    }
}

// Get time in millisecond
double Chrono::getTimeInMilliseconds() const {
    // Time perf
    struct timeval timing;
    struct timezone timeZone; // obsolet

    // Get current time
    gettimeofday(&timing, &timeZone);

    // seconds and in microseconds
    return ((double) timing.tv_sec + timing.tv_usec / 1e6);
}

// Print on a stream
std::ostream& operator << (std::ostream& o, const Chrono c) {
    o << c.get();
    return o;
}

