--Weapon pannels
--(well edited to be item pannels now LOL)
--by Callmore
--edited by logan so it doesnt conflict with call's pannels

freeslot("S_VL2ITEM_PANNEL", "S_VL2ITEM_PANNELD", "MT_VL2ITEM_PANNEL")

local ITEMPANOFFFLAT = "VL2ITEMB"
local ITEMPANONFLAT = "VL2ITEMA"

local function isAlone()
	local count = 0
	for p in players.iterate do
		if p.valid and not p.spectator then
			count = $+1
			if count == 2 then return false end
		end
	end
	--print("Found only one player")
	return true
end

local function tryUseItemPannel(mo, mot)
	if not (mot and mot.valid
	and mot.player and mot.player.valid
	and not mot.player.spectator) then
		return true
	end
	if mo.state ~= S_VL2ITEM_PANNEL then return true end
	
	if P_CanPickupItem(mot.player, 1)
	and P_IsObjectOnGround(mot) then
		mot.player.kartstuff[k_itemroulette] = 1
		mo.state = S_VL2ITEM_PANNELD
		S_StartSound(mot, sfx_ncitem)
		mo.subsector.sector.floorpic = ITEMPANOFFFLAT
		return true
	end
	return true
end

local function itemPannelThink(mo)
	if not (mo.subsector and mo.subsector.valid
	and mo.subsector.sector and mo.subsector.sector.valid) then
		return
	end
	local sect = mo.subsector.sector
	if mo.state == S_VL2ITEM_PANNEL then
		sect.floorpic = ITEMPANONFLAT
		for mo2 in sect.thinglist() do
			tryUseItemPannel(mo, mo2)
			if mo.state == S_VL2ITEM_PANNELD then
				if isAlone() then
					mo.tics = -1
				end
				break
			end
		end
	else
		sect.floorpic = ITEMPANOFFFLAT
	end
end

addHook("MobjThinker", itemPannelThink, MT_VL2ITEM_PANNEL)