/*!
  \file
  \brief タイムスタンプ取得関数

  \author Satofumi KAMIMURA

  $Id: ticks.cpp 1441 2009-10-23 08:49:31Z satofumi $
*/

#include "ticks.h"
#include "EventScheduler.h"
#include "MonitorDataHandler.h"
#include "LogNameHolder.h"
#include "system_ticks.h"

using namespace qrk;
using namespace std;


namespace
{
  class TicksInit
  {
  public:
    ExecutionType::Type type;
    MonitorDataHandler* handler;


    TicksInit(void) : type(ExecutionType::object()->type()), handler(NULL)
    {
      if ((type == ExecutionType::Recording) ||
          (type == ExecutionType::Playback)) {
        string log_name = LogNameHolder::object()->name("mTicks");
        handler = new MonitorDataHandler(log_name, type);
      }
    }


    ~TicksInit(void)
    {
      delete handler;
    }
  };
}


int qrk::ticks(void)
{
  static TicksInit ticks_init;
  static ExecutionType::Type type = ticks_init.type;

  if (type == ExecutionType::Simulation) {
    // シミュレーション動作
    // EventScheduler 内部でのみ呼び出されるため、ロックは不要
    static EventScheduler event_scheduler;
    int current_ticks = event_scheduler.ticks();

    return current_ticks;
  }

  int ticks_msec = 0;
  if (type != ExecutionType::Playback) {
    ticks_msec = system_ticks();
  }

  if ((type == ExecutionType::Recording) ||
      (type == ExecutionType::Playback)) {
    ticks_init.handler->fetch(ticks_msec);
  }
  return ticks_msec;
}
