/*
  時間管理
  Satofumi KAMIMURA
  $Id: timeUtils.cpp 286 2008-10-20 09:40:22Z satofumi $
*/

#include "timeUtils.h"
#include "detect_os.h"
#ifdef Linux
#include <unistd.h>
#include <sys/time.h>
#else
#include <windows.h>
#include <time.h>
#endif

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#if !HAVE_CONFIG_H || HAVE_LIBSDL
#include <SDL.h>
#endif


static bool is_realDevice = true;
static double delay_magnify = 1.0;
static unsigned long delay_const = 1000;


void VXV::set_DelayTimeMagnify(double magnify) {
  delay_magnify = magnify;
  delay_const = static_cast<unsigned long>(1000.0 / delay_magnify);
}


void VXV::set_MonitorMode(bool realDevice) {
  is_realDevice = realDevice;
}


void VXV::Delay(unsigned long msec) {
  unsigned long delay = delay_const * msec;
  if (is_realDevice || (delay > 1000)) {
#ifdef Linux
    usleep(delay);
#else
    Sleep(delay / 1000);
#endif
  }
}


unsigned long VXV::GetTicks(void) {
  unsigned long ticks = 0;

#if !HAVE_CONFIG_H || HAVE_LIBSDL
  ticks = SDL_GetTicks();

#elif defined Linux
  // Linux で SDL がない場合の実装。最初の呼び出しは 0 を返す
  static unsigned long first_ticks = 0;
  struct timeval tvp;
  gettimeofday(&tvp, NULL);
  unsigned long global_ticks = tvp.tv_sec * 1000 + tvp.tv_usec / 1000;
  if (first_ticks == 0) {
    first_ticks = global_ticks;
  }
  ticks = global_ticks - first_ticks;

#else
  ticks = static_cast<unsigned long>(clock() / (CLOCKS_PER_SEC / 1000.0));
#endif
  return ticks;
}
