#pragma once
#include "squirrel/SquirrelEx.h"
#include "Actor/Object/CharacterObject.h"

static CharacterObject *GetCharacterObject(HSQUIRRELVM v)
{
    SQUserPointer ptr;
    sq_getuserpointer(v, 2, &ptr);
    CharacterObject *obj = (CharacterObject *)ptr;
    return obj;
}

static SQInteger SQR_GetState(HSQUIRRELVM v)
{
    CharacterObject *obj = GetCharacterObject(v);
    sq_pushinteger(v, obj->_StateMachine->GetState());
    return 1;
}

static SQInteger SQR_SetState(HSQUIRRELVM v)
{
    CharacterObject *obj = GetCharacterObject(v);
    SQInteger state;
    sq_getinteger(v, 3, &state);
    obj->_StateMachine->ChangeState(state);
    return 0;
}

static SQInteger SQR_SetAction(HSQUIRRELVM v)
{
    CharacterObject *obj = GetCharacterObject(v);
    const SQChar *ActionNameBuf;
    sq_getstring(v, 3, &ActionNameBuf);
    obj->_AnimationManager->SetAction(ActionNameBuf);
    return 0;
}

static void RegisterCharacterObjectNutApi(const SQChar *funcName, SQFUNCTION funcAddr, HSQUIRRELVM v)
{
    sq_pushroottable(v);
    sq_pushstring(v, funcName, -1);
    sq_newclosure(v, funcAddr, 0);
    sq_newslot(v, -3, false);
    sq_poptop(v);
}

static void RegisterCharacterObject()
{
    SDL_Log("初始化 角色对象-松鼠脚本!");
    HSQUIRRELVM v = SquirrelEx::GetInstance().GetSquirrelVM();
    // 获取状态
    RegisterCharacterObjectNutApi(_SC("sq_GetState"), SQR_GetState, v);
    // 设置状态
    RegisterCharacterObjectNutApi(_SC("sq_SetState"), SQR_SetState, v);
    // 设置动画
    RegisterCharacterObjectNutApi(_SC("sq_SetAction"), SQR_SetAction, v);
}
