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

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

#include <wx/log.h>

namespace wherigo {

int zobject_MoveTo(lua_State *L) {
  // Get source object name
  lua_getfield(L, 1, "Name");
  const char *srcName = lua_isstring(L, -1) ? lua_tostring(L, -1) : "(unknown)";
  lua_pop(L, 1);

  // Get target container name
  const char *dstName = "(nil)";
  if (lua_istable(L, 2)) {
    lua_getfield(L, 2, "Name");
    dstName = lua_isstring(L, -1) ? lua_tostring(L, -1) : "(unknown)";
    lua_pop(L, 1);

    lua_pushvalue(L, 2);
    lua_setfield(L, 1, "Container");
  }

  wxLogDebug("MoveTo: %s -> %s", srcName, dstName);

  GameEngine::getInstance().rebuildPlayerInventory();
  GameEngine::getInstance().notifyStateChanged();

  return 0;
}

int zobject_Contains(lua_State *L) {
  // self (container) at index 1, item to check at index 2

  lua_getfield(L, 1, "Name");
  const char *containerName = lua_isstring(L, -1) ? lua_tostring(L, -1) : "(unknown)";
  lua_pop(L, 1);

  lua_getfield(L, 2, "Name");
  const char *itemName = lua_isstring(L, -1) ? lua_tostring(L, -1) : "(unknown)";
  lua_pop(L, 1);

  // Check if item's Container is the same as self (container)
  bool contains = false;

  lua_getfield(L, 2, "Container"); // Get item.Container
  if (lua_istable(L, -1)) {
    // Compare by reference - check if it's the same table as self
    contains = lua_rawequal(L, 1, -1);
  }
  lua_pop(L, 1); // pop Container

  wxLogDebug("Contains: %s in %s? -> %s", itemName, containerName, contains ? "true" : "false");
  lua_pushboolean(L, contains ? 1 : 0);
  return 1;
}

} // namespace wherigo

