#include "Scene_MainUi.h"
#include "Asset/Squirrel/SquirrelManager.h"

void Scene_MainUi::Enter()
{
    Scene::Enter();
    HSQUIRRELVM v = SquirrelEx::GetInstance().GetSquirrelVM();
    SQInteger top = sq_gettop(v);
    sq_pushroottable(v);
    sq_pushstring(v, _SC("_MainUI_Enter_"), -1);
    if (SQ_SUCCEEDED(sq_get(v, -2)))
    {
        sq_pushroottable(v);
        sq_pushuserpointer(v, this);
        sq_call(v, 2, SQFalse, SQTrue);
    }
    sq_settop(v, top);
}

void Scene_MainUi::HandleEvents(SDL_Event *event)
{
    SQInteger EventType = -1;
    std::vector<SQInteger> EventData;
    switch (event->type)
    {
        // 鼠标移动
    case SDL_MOUSEMOTION:
    {
        EventType = 0;
        EventData.push_back(event->motion.x);
        EventData.push_back(event->motion.y);
        break;
    }
        // 鼠标按键按下
    case SDL_MOUSEBUTTONDOWN:
    {
        EventType = 1;
        EventData.push_back(event->button.button);
        break;
    }
        // 鼠标按键释放
    case SDL_MOUSEBUTTONUP:
    {
        EventType = 2;
        EventData.push_back(event->button.button);
        break;
    }
        // 鼠标滚轮
    case SDL_MOUSEWHEEL:
    {
        EventType = 3;
        EventData.push_back(event->wheel.y);
        break;
    }
        // 键盘按键按下
    case SDL_KEYDOWN:
    {
        EventType = 4;
        EventData.push_back(event->key.keysym.sym);
        break;
    }
        // 键盘按键释放
    case SDL_KEYUP:
    {
        EventType = 5;
        EventData.push_back(event->key.keysym.sym);
        break;
    }
    }

    HSQUIRRELVM v = SquirrelEx::GetInstance().GetSquirrelVM();
    SQInteger top = sq_gettop(v);
    sq_pushroottable(v);
    sq_pushstring(v, _SC("_MainUI_HandleEvents_"), -1);
    if (SQ_SUCCEEDED(sq_get(v, -2)))
    {
        sq_pushroottable(v);
        sq_pushinteger(v, EventType);
        sq_newarray(v, 0);
        for (SQInteger i = 0; i < EventData.size(); i++)
        {
            sq_pushinteger(v, EventData[i]);
            sq_arrayappend(v, -2);
        }
        sq_call(v, 3, SQFalse, SQTrue);
    }
    sq_settop(v, top);
}

void Scene_MainUi::Update(float deltaTime)
{
    Scene::Update(deltaTime);
    HSQUIRRELVM v = SquirrelEx::GetInstance().GetSquirrelVM();
    SQInteger top = sq_gettop(v);
    sq_pushroottable(v);
    sq_pushstring(v, _SC("_MainUI_Update_"), -1);
    if (SQ_SUCCEEDED(sq_get(v, -2)))
    {
        sq_pushroottable(v);
        sq_pushfloat(v, deltaTime);
        sq_call(v, 2, SQFalse, SQTrue);
    }
    sq_settop(v, top);
}

void Scene_MainUi::Exit()
{
    Scene::Exit();
    HSQUIRRELVM v = SquirrelEx::GetInstance().GetSquirrelVM();
    SQInteger top = sq_gettop(v);
    sq_pushroottable(v);
    sq_pushstring(v, _SC("_MainUI_Exit_"), -1);
    if (SQ_SUCCEEDED(sq_get(v, -2)))
    {
        sq_pushroottable(v);
        sq_call(v, 1, SQFalse, SQTrue);
    }
    sq_settop(v, top);
}

void Scene_MainUi::Render()
{
    Scene::Render();
}
