-- luacheck: globals Character MyModGlobal CLIENT
if not CLIENT then return end

local dump = require("Cyka.dump")
local utils = require("Cyka.utils")
local quickstack = require("Cyka.quickstack")

local function tryLoot()
	MyModGlobal.debugPrint("Trying to loot dead creatures")
	local character = Character.Controlled
	if not character then
		MyModGlobal.debugPrint("No character found")
		return
	end

	local itemTree, err = quickstack.tryBuildCharacterItemTree(character)
	if err then
		MyModGlobal.debugPrint(string.format("Failed to build item tree: %s", err))
		return
	end

	local items = {}
	for _, itcharacter in pairs(Character.CharacterList) do
		if itcharacter.IsDead and itcharacter.Inventory then
			MyModGlobal.debugPrint(string.format("Enqueuing inventory for %s", itcharacter.Name))
			local before = #items
			utils.enqueueInventory(itcharacter.Inventory, items)
			MyModGlobal.debugPrint(string.format("Enqueued %d items for %s", #items - before, itcharacter.Name))
		end
	end

	local errors = quickstack.tryMoveItems(items, itemTree, true)
	if #errors > 0 then
		MyModGlobal.debugPrint(string.format("Failed to move %d items", #errors))
		for _, err in pairs(errors) do
			MyModGlobal.debugPrint(err)
		end
	end
end

return {
	tryLoot = tryLoot,
}
