#pragma once
#include "squirrel.h"
#include "sqstdaux.h"
#include "sqstdblob.h"
#include "sqstdio.h"
#include "sqstdmath.h"
#include "sqstdstring.h"
#include "sqstdsystem.h"
#include <iostream>

template <typename R, typename A, typename... ARG>
R CallInven(A call_addr, const ARG... arguments)
{
    if (!call_addr)
    {
        return R();
    }
    const auto control = reinterpret_cast<R (*)(ARG...)>(call_addr);
    try
    {
        return control(arguments...);
    }
    catch (...)
    {
    }
    return R();
}

// 获取背包
static SQInteger Inven_GetInven(HSQUIRRELVM v)
{
    SQUserPointer P;
    sq_getuserpointer(v, 2, &P);
    void *InvenP = CallInven<void *>(0x80DA28E, P);
    sq_pushuserpointer(v, InvenP);
    return 1;
}

// 获取背包中的项目
static SQInteger Inven_GetItem(HSQUIRRELVM v)
{
    SQUserPointer P;
    sq_getuserpointer(v, 2, &P);
    SQInteger Type, Slot;
    sq_getinteger(v, 3, &Type);
    sq_getinteger(v, 4, &Slot);

    void *ItemP = CallInven<void *>(0x84FC1DE, P, Type, Slot);
    sq_pushuserpointer(v, ItemP);
    return 1;
}

// 删除背包中的项目
static SQInteger Inven_RemoveItem(HSQUIRRELVM v)
{
    SQUserPointer P;
    sq_getuserpointer(v, 2, &P);

    CallInven<void *>(0x080CB7D8, P);
    return 0;
}

// 删除背包中的指定数量的项目
static SQInteger Inven_RemoveItemFormCount(HSQUIRRELVM v)
{
    SQUserPointer P;
    sq_getuserpointer(v, 2, &P);
    SQInteger Type, Slot, Count, Ps, Log;
    sq_getinteger(v, 3, &Type);
    sq_getinteger(v, 4, &Slot);
    sq_getinteger(v, 5, &Count);
    sq_getinteger(v, 6, &Ps);
    sq_getinteger(v, 7, &Log);

    SQInteger Ret = CallInven<int>(0x850400C, P, Type, Slot, Count, Ps, Log);
    sq_pushinteger(v, Ret);
    return 1;
}

// 根据Id获取背包中的物品槽位
static SQInteger Inven_GetItemById(HSQUIRRELVM v)
{
    SQUserPointer P;
    sq_getuserpointer(v, 2, &P);
    SQInteger Idx;
    sq_getinteger(v, 3, &Idx);

    SQInteger Slot = CallInven<int>(0x08505172, P, Idx);
    sq_pushinteger(v, Slot);
    return 1;
}

static SQInteger register_Inven_func(HSQUIRRELVM v, SQFUNCTION f, const char *fname)
{
    sq_pushroottable(v);
    sq_pushstring(v, fname, -1);
    sq_newclosure(v, f, 0); // create a new function
    sq_newslot(v, -3, SQFalse);
    sq_pop(v, 1); // pops the root table
}

static void RegisterInven(HSQUIRRELVM v)
{
    // 获取背包
    register_Inven_func(v, Inven_GetInven, "Sq_Inven_GetInven");
    // 获取背包中的道具
    register_Inven_func(v, Inven_GetItem, "Sq_Inven_GetItem");
    // 删除背包中的项目
    register_Inven_func(v, Inven_RemoveItem, "Sq_Inven_RemoveItem");
    // 根据Id获取背包中的物品槽位
    register_Inven_func(v, Inven_RemoveItemFormCount, "Sq_Inven_RemoveItemFormCount");
    // 根据Id获取背包中的物品槽位
    register_Inven_func(v, Inven_GetItemById, "Sq_Inven_GetItemById");
}