/*!
  \file
  \brief 状態遷移の実行

  \author Satofumi KAMIMURA

  $Id: lua_runStateMachine.cpp 1811 2010-04-30 16:12:05Z satofumi $
*/

#include "lua_runStateMachine.h"
#include "ScriptedStateMachine.h"
#include "LuaHandler.h"
#include "luabindInit.h"
#include "delay.h"

using namespace qrk;
using namespace luabind;
using namespace std;


namespace
{
    class EmptyStateMachine;
    typedef ScriptedStateMachine<EmptyStateMachine> ScriptedState;


    class EmptyStateMachine
    {
        ScriptedState state_machine_;


    public:
        EmptyStateMachine(void) : state_machine_(this)
        {
        }


        ScriptedState& stateMachine(void)
        {
            return state_machine_;
        }
    };


    void luabindStateMachine(lua_State* L)
    {
        module(L)
            [
             class_<EmptyStateMachine>("EmptyStateMachine")
             .def("stateMachine", &EmptyStateMachine::stateMachine),

             class_<ScriptedState>("ScriptedStateMachine")
             .def("changeState", &ScriptedState::changeState)
             .def("changePreviousState", &ScriptedState::changePreviousState)
             ];
    }
}


void qrk::lua_runStateMachine(lua_State* L, const char* first_state)
{
    EmptyStateMachine state;

    luabindStateMachine(L);

    // 最初の状態を指定して実行
    object global_state = globals(L);
    state.stateMachine().changeState(global_state[first_state]);

    while (true) {
        state.stateMachine().update();
        delay(1);
    }
}
