#include "Chr_StateMachine.h"
#include "Actor/Object/CharacterObject.h"
#include "Asset/Squirrel/SquirrelManager.h"

void Chr_StateMachine::Init(CharacterObject *parent)
{
    chr_Parent = parent;
    addTag(Tag::UPDATE);
    parent->AddChild(this);
}
void Chr_StateMachine::ChangeState(int state)
{
    // 对象存在
    if (chr_Parent)
    {
        // 检查是否可以切换状态
        SQBool CheckFlag = SQFalse;
        HSQUIRRELVM v = SquirrelEx::GetInstance().GetSquirrelVM();
        SQInteger top = sq_gettop(v);
        sq_pushroottable(v);
        sq_pushstring(v, _SC("StateMachine_checkCanChangeState"), -1);
        if (SQ_SUCCEEDED(sq_get(v, -2)))
        {
            sq_pushroottable(v);
            sq_pushuserpointer(v, chr_Parent);
            sq_pushinteger(v, chr_Parent->Job);
            sq_pushinteger(v, state);
            sq_call(v, 4, SQTrue, SQTrue);
            sq_getbool(v, -1, &CheckFlag);
        }
        sq_settop(v, top);

        if (CheckFlag == SQTrue)
        {
            sq_pushroottable(v);
            sq_pushstring(v, _SC("StateMachine_SetState"), -1);
            if (SQ_SUCCEEDED(sq_get(v, -2)))
            {
                sq_pushroottable(v);
                sq_pushuserpointer(v, chr_Parent);
                sq_pushinteger(v, chr_Parent->Job);
                sq_pushinteger(v, state);
                sq_call(v, 4, SQFalse, SQTrue);
            }
            sq_settop(v, top);
            this->State = state;
        }
    }
}

void Chr_StateMachine::Update(float deltaTime)
{
    if (deltaTime == 0.f)
        return;
    if (chr_Parent)
    {
        if (this->State != -1)
        {
            HSQUIRRELVM v = SquirrelEx::GetInstance().GetSquirrelVM();
            SQInteger top = sq_gettop(v);
            sq_pushroottable(v);
            sq_pushstring(v, _SC("StateMachine_ProcState"), -1);
            if (SQ_SUCCEEDED(sq_get(v, -2)))
            {
                sq_pushroottable(v);
                sq_pushuserpointer(v, chr_Parent);
                sq_pushinteger(v, chr_Parent->Job);
                sq_pushinteger(v, this->State);
                sq_pushfloat(v, deltaTime);
                sq_call(v, 5, SQFalse, SQTrue);
            }
            sq_settop(v, top);
        }
    }
}
