// TGF Monitor Commonalities - "Ported" by MIDIMan
// Use with the other LUA_TBX* scripts

freeslot(
	"SPR_TBOX",
	"SPR_TBXX",
	"sfx_tgfbng",
	"S_TGFBOX_CHOOSEEXPLOSION",
	"S_TGFBOX_EXPLODE",
	"S_TGFBOX_BIGEXPLODE",
	"S_TGFBOX_FUSE"
)

rawset(_G, "P_TGFMonitorGiveAbility", function(mo, action, var1, var2)
	if not (mo and mo.valid) then return end
	if not action then return end
	if not var1 then var1 = 0 end
	if not var2 then var2 = 0 end
	
	if not (mo.target and mo.target.valid) then return end
	local player = mo.target.player
	if not (player and player.valid) then return end
	
	// Prevent 2-player bots from stealing your power-ups
	// I don't know why SRB2 doesn't automatically do this for all power-up actions besides A_RingBox
	if (player.bot == BOT_2PAI or player.bot == BOT_2PHUMAN) and player.botleader then
		player = player.botleader
		mo.target = player.mo
	end
	
	action(mo, var1, var2)
end)

sfxinfo[sfx_tgfbng].caption = "Speed burst"

rawset(_G, "P_TGFMonitorFuseThink", function(mobj)
	if not (mobj and mobj.valid) then return end
	
	local newmobj = P_SpawnMobjFromMobj(mobj, 0, 0, 0, mobj.type)
	
	newmobj.flags2 = mobj.flags2
	newmobj.spawnpoint = mobj.spawnpoint
	
	P_RemoveMobj(mobj)
end)

rawset(_G, "P_TGFMonitorTouchSpecial", function(special, toucher)
	if not (special and special.valid
	and toucher and toucher.valid) then
		return
	end
	
	if not special.health then return end
	
	P_KillMobj(special, toucher, toucher)
	return true
end)

rawset(_G, "P_TGFMonitorDeath", function(target, _, _)
	if not (target and target.valid) then return end
	
	if target.info.deathsound then S_StartSound(target, target.info.deathsound) end
end)

// Allow any power-ups to respawn in a non-coop multiplayer game
rawset(_G, "P_TGFPowerUpDeath", function(mobj)
	if not (mobj and mobj.valid) then return end
	
	if CV_FindVar("respawnitem").value and gametype ~= GT_COOP and (modifiedgame or netgame or multiplayer) then
		mobj.fuse = CV_FindVar("respawnitemtime").value*TICRATE + 2
	end
end)

function A_ChooseExplosion(actor, var1, var2)
	if not (actor and actor.valid) then return end
	
	if actor.spawnpoint then
		if (actor.spawnpoint.options & MTF_OBJECTSPECIAL) then
			actor.state = S_TGFBOX_BIGEXPLODE
		else
			actor.state = S_TGFBOX_EXPLODE
		end
	end
end

states[S_TGFBOX_CHOOSEEXPLOSION] =	{SPR_TBXX,	A,				0,	A_ChooseExplosion,	0,	0,	S_NULL}
states[S_TGFBOX_EXPLODE] =			{SPR_TBXX,	A|FF_ANIMATE,	12,	A_Fall,				5,	2,	S_TGFBOX_FUSE}
states[S_TGFBOX_BIGEXPLODE] =		{SPR_TBXX,	G|FF_ANIMATE,	12,	A_Fall,				5,	2,	S_TGFBOX_FUSE}
states[S_TGFBOX_FUSE] =				{SPR_NULL,	A,				-1,	nil,				0,	0,	S_NULL}
