--Drastically increases availability of item pickups
--Extracted from KLV_Diamond, originally written by Fuckal

--Added optimization -NepDisk

local k_itemroulette = k_itemroulette

local itemboxspawnmod = CV_RegisterVar({
    name = "wa_itemboxspawnmod",
    defaultvalue = "On",
    flags = CV_NETVAR,
    PossibleValue = CV_OnOff
})

local itemboxspawnplayers = CV_RegisterVar({
    name = "wa_itemboxspawnmod_minplayers",
    defaultvalue = 10,
    flags = CV_NETVAR,
    PossibleValue = { MIN = 1, MAX = #players },
})

local function getPlayercount()
	local g = 0

	for p in players.iterate do
		if not p.spectator then
			g = g + 1
		end
    end

	return g
end

local cv_respawntime
local function getItemRespawnTime()
    if not cv_respawntime then
        cv_respawntime = CV_FindVar("respawnitemtime") or { value = 2 }
    end

    return cv_respawntime.value * TICRATE
end


local function K_GiveItem(thing, other)
    if not itemboxspawnmod.value then return end
	--if (cv_dorings) and (cv_dorings == 1) then return end --Not getting rings from item boxes with this on
	local pct = getPlayercount()
    if pct < itemboxspawnplayers.value then return end
	if other.player and not other.player.spectator then
		if P_CanPickupItem(other.player, 1) and (not thing.extravalue1) then
			local RESPAWNTIME = getItemRespawnTime()

			other.player.kartstuff[k_itemroulette] = 1

			-- reduce delay based on how many players are present

			-- huge lobbies often mean that players barely get items in general,
			-- leading to losing players getting swamped with defense items
			-- so, let's reduce the delay for item boxes

			thing.extravalue1 = max(6, RESPAWNTIME - ((TICRATE/8)*max(0, pct - 2))) -- Time until item box respawn in tics
			thing.extravalue2 = thing.state

			-- item explosion
			local explode = mobjinfo[thing.info.damage].mass

			local remains = P_SpawnMobj(thing.x, thing.y,
				((thing.eflags & MFE_VERTICALFLIP) and (thing.z + 3*(thing.height/4) - FixedMul(mobjinfo[explode].height, thing.scale)) or (thing.z + thing.height/4)), explode)
			if thing.eflags & MFE_VERTICALFLIP then
				remains.eflags = ($ | MFE_VERTICALFLIP)
				remains.flags2 = ($ | MF2_OBJECTFLIP)
			end

			remains.destscale = thing.destscale
			P_SetScale(remains, thing.scale)

			remains = P_SpawnMobj(thing.x, thing.y, thing.z, thing.info.damage)

			S_StartSound(remains, thing.info.deathsound)

			return false -- "Kill" item box
		end
	end
	return true -- Do nothing
end -- Close function

local function hideItemBox(mo)
	if not itemboxspawnmod.value then return end
	if mo and mo.valid and mo.extravalue1 then
		if mo.extravalue1 > 1 then
			mo.state = S_INVISIBLE
		else
			mo.state = mo.extravalue2 or S_RANDOMITEM1
		end

		mo.extravalue1 = $ - 1
	end
end

addHook("TouchSpecial",	K_GiveItem,	MT_RANDOMITEM)
addHook("MobjThinker", hideItemBox, MT_RANDOMITEM)

-- Notify players if quicker item respawn is active
local lastnumplayers, lastminplayers
addHook("ThinkFrame", function()
    local numplayers = getPlayercount()
    local minplayers = itemboxspawnplayers.value

    if lastnumplayers == nil then lastnumplayers = numplayers end
    if lastminplayers == nil then lastminplayers = minplayers end

    if lastnumplayers < lastminplayers and numplayers >= minplayers then
        print(string.format("\131Quick Item Respawn:\128 %d Players or above, quicker item respawn has activated.", minplayers))
    elseif lastnumplayers >= lastminplayers and numplayers < minplayers then
        print(string.format("\131Quick Item Respawn:\128 Fewer than %d players, item respawn returned to regular speed.", minplayers))
    end

    lastnumplayers = numplayers
    lastminplayers = minplayers
end)
