/*
 *  Copyright 1994-2022 Olivier Girondel
 *
 *  This file is part of lebiniou.
 *
 *  lebiniou 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 2 of the License, or
 *  (at your option) any later version.
 *
 *  lebiniou 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 lebiniou. If not, see <http://www.gnu.org/licenses/>.
 */

#include "btimer.h"
#include "utils.h"

static enum TimerMode Timer_mode = BT_HARD;

#define GETTIME(v) do { gettimeofday(&v, NULL); } while (0)

extern uint64_t frames;
extern uint8_t  max_fps;


Timer_t *
Timer_new(const char *name)
{
  Timer_t *timer = xcalloc(1, sizeof(Timer_t));

#ifdef DEBUG_TIMERS
  timer->name = name;
#endif
  Timer_start(timer);

  return timer;
}


void
Timer_delete(Timer_t *timer)
{
  xfree(timer);
}


void
Timer_start(Timer_t *timer)
{
  GETTIME(timer->h_start);
  timer->s_start = frames;
}


float
Timer_elapsed(const Timer_t *timer)
{
  float ret;

  if (Timer_mode == BT_HARD) {
    struct timeval now, elapsed;

    GETTIME(now);
    if (timer->h_start.tv_usec > now.tv_usec) {
      now.tv_usec += 1000000;
      now.tv_sec--;
    }
    elapsed.tv_usec = now.tv_usec - timer->h_start.tv_usec;
    elapsed.tv_sec = now.tv_sec - timer->h_start.tv_sec;

    ret = (float)(elapsed.tv_sec + ((float)elapsed.tv_usec / 1e6));
  } else {
    ret = (frames - timer->s_start) / (float)max_fps;
  }

#ifdef DEBUG_TIMERS
  printf("=== %s timer (%s) elapsed: %f\n", (Timer_mode == BT_HARD) ? "Hard" : "Soft", timer->name, ret);
#endif

  return ret;
}


void
Timer_set_mode(const enum TimerMode mode)
{
  Timer_mode = mode;
}
