----- DISABLE PLAYER CONTROL IN MINECARTS -----

/*
To be used with Linedef type 443:
- Put "MM_CONTROL_OFF" as the string to disable player control
- Put "MM_CONTROL_ON" to enable player control
- Put "MM_CONTROL_TOGGLE" to toggle player control
  - This last one should exclusively be called with "Each time on entry"

The control state only AFFECTS you as long as you're in a minecart,
but is still MAINTAINED until it is modified again. (Or you respawn,
in which case it's reset to Off)

Meaning, if you disable player control on a minecart, then the player
exits the minecart track without it being re-enabled, they'll regain control.
But the moment they get on another minecart, they'll lose control again.
*/

-- Player initialization
local function mmControl_Spawn(p)
	if not (p and p.valid) then return end
	if not (p.mo and p.mo.valid) then return end
	p.mm_control = false
end

addHook("PlayerSpawn", mmControl_Spawn)

-- Apply FULLSTASIS effect
local function mmControl_Think()
	for p in players.iterate do
		if not (p and p.valid) then continue end
		if not (p.mo and p.mo.valid) then continue end
		if p.mm_control and (p.powers[pw_carry] == CR_MINECART) then
			p.pflags = $ | PF_FULLSTASIS
			p.cmd.forwardmove = 0
			p.cmd.sidemove = 0
			p.cmd.buttons = 0
		end
	end
end

addHook("PreThinkFrame", mmControl_Think)

-- Disable/enable player control
local function mmControl_Linedef(line, mo, sector)
	if not (mo and mo.valid) then return end
	if not (mo.player and mo.player.valid) then return end
	local p = mo.player
	if string.sub(line.stringargs[0], -3) == "OFF" then
		p.mm_control = true
	elseif string.sub(line.stringargs[0], -2) == "ON" then
		p.mm_control = false
	elseif string.sub(line.stringargs[0], -6) == "TOGGLE" then
		p.mm_control = not $
	end
end

addHook("LinedefExecute", mmControl_Linedef, "MM_CONTROL_OFF")
addHook("LinedefExecute", mmControl_Linedef, "MM_CONTROL_ON")
addHook("LinedefExecute", mmControl_Linedef, "MM_CONTROL_TOGGLE")