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

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

---@param invSlot InventorySlot
local function tryUnloadSlot(invSlot)
	---@type table<Barotrauma.ItemPrefab, boolean>
	local toUnloadByPrefab = {}

	local itemInventory = invSlot.item.OwnInventory
	if not itemInventory then
		MyModGlobal.debugPrint("No inventory for item")
		return
	end
	MyModGlobal.debugPrint(string.format("Enqueuing inventory %s", tostring(itemInventory)))

	local toUnload = utils.enqueueInventory(itemInventory, {
		itemPredicate = function(item)
			toUnloadByPrefab[item.Prefab] = true
			return true
		end,
		recurse = false,
	})
	MyModGlobal.debugPrint(string.format("Moving %d items to unload %s", #toUnload.itemQueue, tostring(invSlot.item)))

	-- Where can we put our toUnload items?
	local nearbySlots = invSlot:getNearbySlots(function(islot)
		local isEmpty = not islot.item
		if isEmpty then return true end

		for prefab, _ in pairs(toUnloadByPrefab) do
			local canFit = islot:canFit(prefab)
			if canFit then return true end
		end
		return false
	end)
	MyModGlobal.debugPrint(string.format("Into %d nearby slots", #nearbySlots))


	for _, iitem in ipairs(toUnload.itemQueue) do
		for _, nearbySlot in ipairs(nearbySlots) do
			local canAccept = nearbySlot:canFit(iitem.Prefab)
			if canAccept then
				utils.enqueueMove(iitem, nearbySlot)
				break
			end
		end
	end
end

local function tryUnloadCursorItem()
	local slots, err = utils.getSlotsUnderCursor()
	if err then
		MyModGlobal.debugPrint(string.format("Error getting inventory slot: %s", err))
		return
	end

	if not slots or #slots == 0 then
		MyModGlobal.debugPrint("No items in slot")
		return
	end

	for _, slot in ipairs(slots) do
		tryUnloadSlot(slot)
	end
end

return {
	tryUnloadCursorItem = tryUnloadCursorItem,
}
