#pragma once
#include "PVF_IO.hpp"

static SQInteger Asset_LoadScript(HSQUIRRELVM v)
{
    // 获得路径
    const SQChar *Path;
    sq_getstring(v, 2, &Path);

    PVF_IO *pvf = new PVF_IO(Path);
    pvf->Init();
    sq_pushuserpointer(v, pvf);
    return 1;
}

static SQInteger Asset_GetPvfFileSize(HSQUIRRELVM v)
{
    // 获取PVF指针
    SQUserPointer Pvfbuf;
    // 获得路径
    const SQChar *Path;
    sq_getuserpointer(v, 2, &Pvfbuf);
    sq_getstring(v, 3, &Path);

    PVF_IO *Pvf = (PVF_IO *)Pvfbuf;
    auto Info = Pvf->GetFileInfo(Path);
    if (Info)
        sq_pushinteger(v, Info->Length);
    else
        sq_pushnull(v);
    return 1;
}

static SQInteger Asset_GetPvfFile(HSQUIRRELVM v)
{
    // 获取PVF指针
    SQUserPointer Pvfbuf, blobp;
    // 获得路径
    const SQChar *Path;
    sq_getuserpointer(v, 2, &Pvfbuf);
    sq_getstring(v, 3, &Path);
    sqstd_getblob(v, 4, &blobp);

    PVF_IO *Pvf = (PVF_IO *)Pvfbuf;
    Pvf->LoadFileToBlob(v, Path, blobp);
    return 0;
}

static SQInteger Asset_GetPvfBinString(HSQUIRRELVM v)
{
    // 获取PVF指针
    SQUserPointer Pvfbuf;
    // 获得Key
    SQInteger Key;
    sq_getuserpointer(v, 2, &Pvfbuf);
    sq_getinteger(v, 3, &Key);

    PVF_IO *Pvf = (PVF_IO *)Pvfbuf;
    std::string value = Pvf->GetBinString(Key);

    sq_pushstring(v, value.c_str(), value.length());
    return 1;
}

static SQInteger Asset_GetPvfLoadString(HSQUIRRELVM v)
{
    // 获取PVF指针
    SQUserPointer Pvfbuf;
    // 获取类型
    const SQChar *Type;
    // 获得Key
    const SQChar *Key;
    sq_getuserpointer(v, 2, &Pvfbuf);
    sq_getstring(v, 3, &Type);
    sq_getstring(v, 4, &Key);

    PVF_IO *Pvf = (PVF_IO *)Pvfbuf;

    std::string value = Pvf->GetLoadString(Type, Key);
    value = value.c_str();

    sq_pushstring(v, value.c_str(), value.length());
    return 1;
}

void RegisterAssetNutApi(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);
}

void RegisterAsset(HSQUIRRELVM v)
{
    RegisterAssetNutApi(_SC("Asset_LoadScript"), Asset_LoadScript, v);
    RegisterAssetNutApi(_SC("Asset_GetPvfFileSize"), Asset_GetPvfFileSize, v);
    RegisterAssetNutApi(_SC("Asset_GetPvfFile"), Asset_GetPvfFile, v);
    RegisterAssetNutApi(_SC("Asset_GetPvfBinString"), Asset_GetPvfBinString, v);
    RegisterAssetNutApi(_SC("Asset_GetPvfLoadString"), Asset_GetPvfLoadString, v);
}