#include "LuaStateHandler.hpp"
#include "version.h"
#include "Debug.hpp"

void printVersionString()
{
    TSE_LOG("TSE: " + TSE_VERSION_STRING);
}

void TSE::LuaStateHandler::InitLuaState()
{
    L = luaL_newstate();
    luaL_openlibs(L);

    luabridge::getGlobalNamespace(TSE_LUA_STATE)
        .beginNamespace("engine")
            .addProperty("version", getVersionString)
            .addFunction("printVersion", printVersionString)
        .endNamespace();
}

void TSE::LuaStateHandler::RunLuaString(string cmd)
{
    int res = luaL_dostring(L, cmd.c_str());
    if (res != LUA_OK)
    {
        const char* err = lua_tostring(L, -1);
        TSE_ERROR(err ? err : "<unknown lua error>");
        lua_pop(L,1);
    }
}

void TSE::LuaStateHandler::RunLuaScript(string path)
{
    int res = luaL_dofile(L, path.c_str());
    if (res != LUA_OK)
    {
        const char* err = lua_tostring(L, -1);
        TSE_ERROR(err ? err : "<unknown lua error>");
        lua_pop(L,1);
    }
}
