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

Global_Game::Global_Game()
{
}
Global_Game::~Global_Game()
{
}

void Global_Game::InitFont()
{
    HSQUIRRELVM v = SquirrelEx::GetInstance().GetSquirrelVM();
    SQInteger top = sq_gettop(v);

    sq_pushroottable(v);
    sq_pushstring(v, _SC("_InitFont_"), -1);
    if (SQ_SUCCEEDED(sq_get(v, -2)))
    {
        sq_pushroottable(v);
        if (SQ_SUCCEEDED(sq_call(v, 1, SQTrue, SQTrue)))
        {
            sq_pushnull(v);
            while (SQ_SUCCEEDED(sq_next(v, -2)))
            {
                const SQChar *path = nullptr;
                SQInteger size = 0;

                if (sq_gettype(v, -1) == OT_TABLE)
                {
                    // 获取path
                    sq_pushstring(v, _SC("path"), -1);
                    if (SQ_SUCCEEDED(sq_get(v, -2)))
                    {
                        sq_getstring(v, -1, &path);
                        sq_pop(v, 1);
                    }

                    // 获取size
                    sq_pushstring(v, _SC("size"), -1);
                    if (SQ_SUCCEEDED(sq_get(v, -2)))
                    {
                        sq_getinteger(v, -1, &size);
                        sq_pop(v, 1);
                    }

                    // 初始化ttf字体资源
                    TTF_Font *FontBuf = TTF_OpenFont(path, size);
                    if (!FontBuf)
                    {
                        SDL_LogError(0, "字体加载失败: %s", TTF_GetError());
                        continue;
                    }
                    Fonts.push_back(FontBuf);
                }

                sq_pop(v, 2);
            }
            sq_pop(v, 1);
        }
    }
    sq_settop(v, top);
}

void Global_Game::Init()
{
    InitFont();

    // TTF_Font *FontBuf = TTF_OpenFont("Fonts/NotoSansSC-Regular.otf", 24);
    // TTF_Font *FontBuf = TTF_OpenFont("Fonts/calibri.ttf", 24);


}

void Global_Game::InitGame()
{
    // 读取角色配置文件
    CharacterConfigs = GlobalCharacterScript::InitCharacterLst();
    // 读取装备配置文件
    EquipmentPathMap = GlobalEquipmentScript::InitEquipmentLst();
    // 读取怪物配置文件
    MonsterPathMap = GlobalMonsterScript::InitMonsterLst();

    // 初始化松鼠脚本管理器
    SquirrelManager::GetInstance().Init();

    //  读取存档
    SavaManager::GetInstance().Init();
    // 游戏初始化完成标志
    InitFlag = true;
}

GlobalMonsterScript::MonsterConfig Global_Game::GetMonsterInfo(int id)
{
    if (!InitFlag)
    {
        SDL_LogError(0, "游戏未初始化");
        return GlobalMonsterScript::MonsterConfig();
    }
    if (MonsterInfoMap.count(id))
        return MonsterInfoMap[id];
    if (!MonsterPathMap.count(id))
    {
        SDL_LogError(0, "怪物ID不存在");
        return GlobalMonsterScript::MonsterConfig();
    }
    std::string path = MonsterPathMap[id];
    GlobalMonsterScript::MonsterConfig MonsterConfig = GlobalMonsterScript::ReadMonsterConfig(path);
    MonsterConfig.id = id;
    MonsterInfoMap[id] = MonsterConfig;
    return MonsterConfig;
}