/*****************************************************************************
 * $LastChangedDate: 2011-04-23 21:07:07 -0400 (Sat, 23 Apr 2011) $
 * @file
 * @author  Jim E. Brooks  http://www.palomino3d.org
 * @brief   A part of the C++ core that calls Lua functions.
 * @remarks Another part is the program module (startup).
 *//*
 * LEGAL:   COPYRIGHT (C) 2008 JIM E. BROOKS
 *          THIS SOURCE CODE IS RELEASED UNDER THE TERMS
 *          OF THE GNU GENERAL PUBLIC LICENSE VERSION 2 (GPL 2).
 *****************************************************************************/

#define GLUE_CORE2LUA_CC 1
#include <vector>
#include "base/module.hh"
using namespace base;
#include "lua_bind/module.hh"
#include "lua_bind/interpreter.hh"
using namespace lua::interpreter;
#include "glue/module.hh"
#include "glue/core2lua.hh"

namespace glue {

////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////  Core2Lua  ///////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

Core2Lua* Core2Lua::msInstance;

/*****************************************************************************
 * ctor/dtor.
 * Install listeners that propagate events from C++ to Lua.
 *****************************************************************************/
Core2Lua::Core2Lua( void )
{
    EVENT_DESTROY_OBJECT.Listen( new DestroyObjectListener( *this ) );
    EVENT_COLLISION.Listen(      new CollisionListener( *this ) );
}

Core2Lua::~Core2Lua()
{
    // For a Singleton, skip unlistening.
}

/*****************************************************************************
 * Listen for the DestroyObject event and propagate to Lua.
 *****************************************************************************/
void
Core2Lua::DestroyObjectListener::operator()( shptr<Object> object )
{
CHECK_TYPESIG(object,TYPESIG_OBJECT);

    const LuaNumber rawPtr = LuaNumber( reinterpret_cast<long>( object.PTR() ) );
    std::vector<LuaNumber> args;
    args.push_back( rawPtr );
    GET_LUA().CallLuaFunc( LUABIND_TABLE_NAME, "HandleDestroyObject", args );
}

/*****************************************************************************
 * Listen for the collision event and propagate to Lua.
 *****************************************************************************/
void
Core2Lua::CollisionListener::operator()( collision::Events::ObjectPair objectPair )
{
CHECK_TYPESIG(objectPair.first,TYPESIG_OBJECT);
CHECK_TYPESIG(objectPair.second,TYPESIG_OBJECT);

    const LuaNumber rawPtr1 = LuaNumber( reinterpret_cast<long>( objectPair.first.PTR()  ) );
    const LuaNumber rawPtr2 = LuaNumber( reinterpret_cast<long>( objectPair.second.PTR() ) );
    std::vector<LuaNumber> args;
    args.push_back( rawPtr1 );
    args.push_back( rawPtr2 );
    GET_LUA().CallLuaFunc( LUABIND_TABLE_NAME, "HandleCollision", args );
}

} // namespace glue
