#include "lua/ztimer.h"
#include "lua/game_engine.h"

extern "C" {
#include <lua.h>
}

#include <wx/log.h>

namespace wherigo {

int ztimer_Start(lua_State *L) {
  lua_getfield(L, 1, "Name");
  const char *name = lua_isstring(L, -1) ? lua_tostring(L, -1) : "(unnamed)";
  lua_pop(L, 1);

  lua_getfield(L, 1, "Duration");
  lua_Number duration = lua_isnumber(L, -1) ? lua_tonumber(L, -1) : 0;
  lua_pop(L, 1);

  wxLogDebug("Timer Start: %s (Duration: %.1f sec)", name, duration);

  lua_pushboolean(L, 1);
  lua_setfield(L, 1, "Running");

  GameEngine::getInstance().notifyStateChanged();

  return 0;
}

int ztimer_Stop(lua_State *L) {
  lua_getfield(L, 1, "Name");
  const char *name = lua_isstring(L, -1) ? lua_tostring(L, -1) : "(unnamed)";
  lua_pop(L, 1);

  wxLogDebug("Timer Stop: %s", name);

  lua_pushboolean(L, 0);
  lua_setfield(L, 1, "Running");

  GameEngine::getInstance().notifyStateChanged();

  return 0;
}

int ztimer_Reset(lua_State *L) {
  lua_getfield(L, 1, "Name");
  const char *name = lua_isstring(L, -1) ? lua_tostring(L, -1) : "(unnamed)";
  lua_pop(L, 1);

  wxLogDebug("Timer Reset: %s", name);

  lua_pushboolean(L, 0);
  lua_setfield(L, 1, "Running");

  GameEngine::getInstance().notifyStateChanged();

  return 0;
}

} // namespace wherigo

