/***
Parry

OVERCOMPLICATED CODE AHHH

(DISCLAIMER: This was made inspired by SFA: Third Strike's parrying mechanic
and I am not 100% familar with the technicalities of it and
only made this with the loose understanding I have! So I don't know about 
red parries and I don't know how EVO moment #37 works)

By default, you can "parry" every hazard (incl. map hazards) ..
.. EXCEPT Jawz and SPBs. Which can be changed via CVARs.
***/

local PARRYING_DURATION = TICRATE/2 -- Half a second
local PARRY_NOTIFY = 2*TICRATE -- For HUD display
local PUNISH_TIMER = 4*TICRATE -- Punish timer for parrying SPBs/Jawz

/**
CVARS
**/
local PARRY_ENABLED = CV_RegisterVar({ 
	name = "parry",
	defaultvalue = "on",
	flags = CV_NETVAR,
	possiblevalue = CV_OnOff
})

local PARRY_RACE_MESSAGE = CV_RegisterVar({ 
	name = "parry_racemessage",
	defaultvalue = "on",
	flags = CV_NETVAR,
	possiblevalue = CV_OnOff
})

local SPB_PARRY = CV_RegisterVar({ 
	name = "parry_spb",
	defaultvalue = "off",
	flags = CV_NETVAR|CV_CALL,
	possiblevalue = CV_OnOff,
	func = function(cv)
		local str = (cv.value == 1) and "\131 on" or "\133 off"
		print("\135* SPB parries are" .. str)
	end 
})

local JAWZ_PARRY = CV_RegisterVar({
	name = "parry_jawz",
	defaultvalue = "off",
	flags = CV_NETVAR|CV_CALL,
	possiblevalue = CV_OnOff,
	func = function(cv)
		local str = (cv.value == 1) and "\131 on" or "\133 off"
		print("\135* Jawz parries are" .. str)
	end 
})

local PARRY_FRAMES = CV_RegisterVar({
	name = "parry_frames_config",
	defaultvalue = "5",
	flags = CV_NETVAR,
	possiblevalue = CV_Natural
})

local PARRY_PUNISH = CV_RegisterVar({
	name = "parry_punish",
	defaultvalue = "on",
	flags = CV_NETVAR|CV_CALL,
	possiblevalue = CV_OnOff,
	func = function(cv)
		local str = (cv.value == 1) and "\131 on" or "\133 off"
		print("\135* Parry punishes are" .. str)
	end 
})

// If you're a madman
local PARRY_SPAM = CV_RegisterVar({
	name = "parry_spamfilter",
	defaultvalue = "on",
	flags = CV_NETVAR,
	possiblevalue = CV_OnOff
})

// Local CVARs
local PARRY_HUD_NOTIFY = CV_RegisterVar({
	name = "parry_hud_notify",
	defaultvalue = "on",
	possiblevalue = CV_OnOff
})

/**
COMMANDS
**/
local function Parry_ConfigFrames(p, frames)
	frames = tonumber(frames) or 1
	
	if(frames <= 0 or frames > 10) then
		CONS_Printf(p, "\133* Please enter a number from \1301\133 to \13010\133.")
		return
	end
	
	COM_BufInsertText(server, "parry_frames_config ".. frames)
	print("\135* Parry duration set to \130"..frames.. "\135 frame(s).")
	
end
COM_AddCommand("parry_frames", Parry_ConfigFrames, 1)

local function Parry_SwitchOn(p)
	print("\135* Parrying switched \131on.")
	COM_BufInsertText(server, "parry on")
end
COM_AddCommand("parryon", Parry_SwitchOn, 1)

local function Parry_SwitchOff(p)
	print("\135* Parrying switched \133off.")
	COM_BufInsertText(server, "parry off")
end
COM_AddCommand("parryoff", Parry_SwitchOff, 1)

/**
FREESLOT
**/
freeslot("sfx_prry", "sfx_ltsgo", "SPR_PRRY", 
"S_PARRYFLASH1","S_PARRYFLASH2","S_PARRYFLASH3", "S_PARRYFLASH4") -- Normal parry, iconic SF3S SFX, sprites, states

states[S_PARRYFLASH1] = {SPR_PRRY, FF_TRANS50, 1, nil, 0, 0, S_PARRYFLASH2}
states[S_PARRYFLASH2] = {SPR_NULL, FF_TRANS50|1, 1, nil, 0, 0, S_PARRYFLASH3}
states[S_PARRYFLASH3] = {SPR_PRRY, FF_TRANS50, 1, nil, 0, 0, S_PARRYFLASH4}
states[S_PARRYFLASH4] = {SPR_NULL, FF_TRANS50, 1, nil, 0, 0, S_PARRYFLASH1}
/**
FUNCTIONS
**/

// Iniitialise parry variables
local function Parry_InitVars(p)
	p.PARRY = {
		IS_PARRYING = false,
		PARRY_TIMER = 0,
		PARRY_SHIELD= nil,
		HAS_PARRIED = false,
		PARRY_CALM_DOWN = 0,
		PARRY_FRAME_COUNT = nil,
		INSTASHIELD = 0,
		HUD_TIMER = 0,
		PUNISH_TIMER = 0,
		MEGA_PARRY = false,
		BALLOON_PARRY = false, // snort
		
		LASTITEMFRAME = nil,
		ITEMFRAME = nil,
		
		// Spam check
		LAST_PARRY = nil,
		SPAM_COUNT = 0,
		SPEC_RESET = false
	}
end


local function Parry_StartParry(p, inflictor)
	if(p.PARRY and p.PARRY.IS_PARRYING and not p.PARRY.HAS_PARRIED
   and p.playerstate ~= PST_DEAD and not P_CheckDeathPitCollide(p.mo)) then
			
		p.powers[pw_flashing] = 10
		
		local COOL_PARRY = false
		
		if(inflictor and inflictor.type == MT_BALLOON) then
			p.PARRY.BALLOON_PARRY = true
		elseif(inflictor and inflictor.type == MT_SPBEXPLOSION) then
			if(not SPB_PARRY.value) then return nil end
			
			p.PARRY.MEGA_PARRY = true
			COOL_PARRY = true
			
		elseif(inflictor and (inflictor.type == MT_JAWZ or inflictor.type == MT_JAWZ_SHIELD)) then
			if(not JAWZ_PARRY.value) then return nil end
			COOL_PARRY = true
		else
			p.PARRY.MEGA_PARRY = false
			p.PARRY.BALLOON_PARRY = false
		end
		
		if(COOL_PARRY) then
		
			if(p.PARRY.BALLOON_PARRY) then p.PARRY.BALLOON_PARRY = false end
			
			if(PARRY_PUNISH.value) then
				p.PARRY.PUNISH_TIMER = PUNISH_TIMER
			end
			
			if(p.PARRY.MEGA_PARRY) then
				S_StartSound(p.mo, sfx_ltsgo, p)
			end
		end
		
		p.PARRY.HUD_TIMER = PARRY_NOTIFY
		p.PARRY.HAS_PARRIED = true
		p.PARRY.PARRY_TIMER = PARRYING_DURATION
		
		S_StartSoundAtVolume(p.mo, sfx_prry, INT32_MAX, p)
		return false
   end
   return nil
end

// Parry check (Spin/explosion)
local function Parry_ShouldParrySpin(player, inflictor, source)
	if not PARRY_ENABLED.value then return end
	
	local p = (player.player == nil) and player or player.player
	if not p.mo then return end
	if not p.mo.valid then return end

	local action = Parry_StartParry(p, inflictor)
	return action
end

addHook("ShouldDamage", Parry_ShouldParrySpin, MT_PLAYER)
addHook("ShouldSpin", Parry_ShouldParrySpin, MT_PLAYER)
addHook("ShouldExplode", Parry_ShouldParrySpin, MT_PLAYER)

// Balloons
local function Parry_ShouldParryBalloons(mo, mo2)

	if not PARRY_ENABLED.value then return end
	if mo2.type ~= MT_PLAYER then return end
	
	local p = mo2.player
	if not mo2 and not mo2.valid then return end
	
	local action = Parry_StartParry(p, mo)
	
	if(action == false) then
		P_KillMobj(mo)
		return true
	else
		return nil
	end
end
addHook("TouchSpecial", Parry_ShouldParryBalloons, MT_BALLOON)

local function Parry_SpawnShield(p)
	
	if not p.PARRY then return end
	p.PARRY.PARRY_SHIELD = P_SpawnMobj(p.mo.x, p.mo.y, p.mo.z, MT_THOK)
	p.PARRY.PARRY_SHIELD.flags = MF_NOGRAVITY|MF_NOCLIPHEIGHT
	p.PARRY.PARRY_SHIELD.tics = -1
	p.PARRY.PARRY_SHIELD.state = S_PARRYFLASH1

	p.PARRY.PARRY_SHIELD.color = p.skincolor
	p.PARRY.PARRY_SHIELD.target = p.mo

end
	
// """""Animate""""" parry
local function Parry_AnimateParryV2(p)
	if not p.PARRY then return end

	if(p.PARRY.PARRY_TIMER > 0) then
		p.PARRY.PARRY_TIMER = $ - 1
		
		if(p.PARRY.PARRY_TIMER > 20) then
			K_DoInstashield(p)
		end
		
	else
		p.PARRY.HAS_PARRIED = false
	end
end

local function Parry_AnimateParry(p)
	if(p.PARRY.HUD_TIMER >= TICRATE) then
		p.mo.color = (leveltime % 2) and ((p.PARRY.MEGA_PARRY) and SKINCOLOR_MINT or SKINCOLOR_JAWZ) or SKINCOLOR_WHITE
	else
		p.mo.color = p.skincolor
	end
	
	if(p.PARRY.HUD_TIMER == 0) then
		p.PARRY.MEGA_PARRY = false
		p.PARRY.BALLOON_PARRY = false
	end
	
	p.PARRY.HUD_TIMER = $ - 1
end

// Cough
local function Parry_PunishHandler(p, reason)
	if(P_IsObjectOnGround(p.mo)) then
	
		local strength = (reason == nil) and 1000 or 600
		p.mo.friction = (p.kartstuff[k_spinouttimer] == 0) and $ - strength or $
		K_SpawnWipeoutTrail(p.mo, true)
		if (leveltime % 6 == 0)
			S_StartSound(p.mo, sfx_cdfm70)
		end			
	end
end

local function Parry_SpamCheck(p)
	if(p.PARRY.SPAM_COUNT >= 5 and PARRY_SPAM.value == 1) then
		Parry_PunishHandler(p, "spam")
	end
end

local function Parry_InputCheck(p)
	
	local input = _SameFrameBtnCheck(p)
	return (input ~= nil 
			and p.kartstuff[k_itemroulette] == 0
			and p.PARRY.ITEMFRAME  == KITEM_NONE 
			and p.PARRY.LASTITEMFRAME == KITEM_NONE
			and p.kartstuff[k_spinouttimer] == 0 
			and p.kartstuff[k_invincibilitytimer] == 0
			and p.powers[pw_flashing] == 0 
			and p.PARRY.PUNISH_TIMER == 0
			and p.kartstuff[k_growshrinktimer] <= 0 // You're invinc when grown, not shrunk
			and not p.PARRY.IS_PARRYING and p.PARRY.PARRY_CALM_DOWN == 0)
end

local function Parry_ThinkHandler(p)

	if not p.PARRY then
		Parry_InitVars(p)
	end
	if not PARRY_ENABLED.value then return end
	
	if(p.spectator) then
		if(not p.PARRY.SPEC_RESET) then
			Parry_InitVars(p)
			p.PARRY.SPEC_RESET = true
		end
	else
		p.PARRY.SPEC_RESET = false
	end
	if not p.mo then return end
	if not p.mo.valid then return end


	// So you don't immediately parry after using an item
	p.PARRY.ITEMFRAME = p.kartstuff[k_itemtype]
	
	if(p.PARRY.HAS_PARRIED) then
		Parry_AnimateParryV2(p)
	end
	
	if(p.PARRY.PARRY_CALM_DOWN > 0) then
		p.PARRY.PARRY_CALM_DOWN = $ - 1
	end
	
	if(p.PARRY.HUD_TIMER > 0) then
		Parry_AnimateParry(p)
	end
	
	if(p.PARRY.PARRY_FRAME_COUNT ~= nil and p.PARRY.PARRY_FRAME_COUNT >= 0
	   and p.PARRY.PARRY_FRAME_COUNT < PARRY_FRAMES.value+1) then
		p.PARRY.PARRY_FRAME_COUNT = $ + 1
	end	
	
	// Have you parried?
	if(Parry_InputCheck(p)) then
		p.PARRY.IS_PARRYING = true
		p.PARRY.PARRY_CALM_DOWN = 2
		p.PARRY.PARRY_FRAME_COUNT = 0
		
		if(p.PARRY.LAST_PARRY ~= nil and p.PARRY.LAST_PARRY < (3*TICRATE/5)) then
			p.PARRY.SPAM_COUNT = $+1
		end
		p.PARRY.LAST_PARRY = 0
	end
	
	if(p.PARRY.LAST_PARRY ~= nil) then
		p.PARRY.LAST_PARRY = $+1
		
		if(p.PARRY.LAST_PARRY > TICRATE) then
			p.PARRY.SPAM_COUNT = 0
			p.PARRY.LAST_PARRY = nil
		end
	end
	
	Parry_SpamCheck(p)
	
	// These don't come free (unless an admin wants it to)
	if(p.PARRY.PUNISH_TIMER > 0) then
		Parry_PunishHandler(p, nil)
		p.PARRY.PUNISH_TIMER = $-1
	end

	// Teleport shield after its spawned
	if(p.PARRY.PARRY_SHIELD and p.PARRY.PARRY_SHIELD.valid) then
		P_TeleportMove(p.PARRY.PARRY_SHIELD, p.mo.x, p.mo.y, p.mo.z)
		
		p.PARRY.PARRY_SHIELD.colorized = true
		p.PARRY.PARRY_SHIELD.color = p.skincolor
		
		// Kill parry shield
		
		if(p.PARRY.PARRY_FRAME_COUNT == PARRY_FRAMES.value) then
			P_KillMobj(p.PARRY.PARRY_SHIELD)
			p.PARRY.PARRY_SHIELD  = nil
			p.PARRY.IS_PARRYING = false
			p.PARRY.PARRY_FRAME_COUNT = nil
			
			p.mo.colorized = false
			p.mo.color = p.skincolor
		end
	end
	
	if(p.PARRY.IS_PARRYING and p.PARRY.PARRY_SHIELD == nil) then
		Parry_SpawnShield(p)
	end
	
	p.PARRY.LASTITEMFRAME = p.PARRY.ITEMFRAME
	
end

// HUD Drawing
local function Parry_DrawNotify(v, p, c)
	if not p.PARRY then return end
	if not PARRY_ENABLED.value then return end
	if not PARRY_HUD_NOTIFY.value then return end
	
	if(p.PARRY.HUD_TIMER > 0) then
		local v_flags = (p.PARRY.MEGA_PARRY) and V_GREENMAP or V_PINKMAP
		v_flags = (p.PARRY.BALLOON_PARRY) and V_BLUEMAP or $
		local yPos = 95
		
		yPos = (p.PARRY.HUD_TIMER == PARRY_NOTIFY-1) and 105 or 95
		if(p.PARRY.HUD_TIMER <= 10) then
			v_flags = $|(10 - p.PARRY.HUD_TIMER)<<V_ALPHASHIFT
		end

		local str = (p.PARRY.MEGA_PARRY) and "SUPER PARRY!" or "PARRIED!"
		str = (p.PARRY.BALLOON_PARRY == true) and "POP" or $
		
		if(p.PARRY.BALLOON_PARRY) then
			if(p.PARRY.HUD_TIMER > TICRATE) then
				v.drawString(170, yPos, str, v_flags, "thin")
			end
		else
			v.drawString(170, yPos, str, v_flags, "thin")
		end
		
	end
end

/**
HOOKS
**/

addHook("MapLoad", function()
	for p in players.iterate do
		if(not p.PARRY) then
			Parry_InitVars(p)
		else
			Parry_InitVars(p)
		end
		
		
		// In case a map warp happens on a colorized frame or something
		if(p.mo and p.mo.valid) then 
			p.mo.colorized = false
			p.mo.color = p.skincolor		
		end

	end
end)

addHook("ThinkFrame", function()
	for p in players.iterate do
		Parry_ThinkHandler(p)
	end
	
	if(PARRY_RACE_MESSAGE.value and leveltime == 2*TICRATE) then
		chatprint("\135* Press \130ITEM\135 to parry!", true)
	end
end)

hud.add(Parry_DrawNotify, "game")

/**
MISC
**/

//Shut up, I know this sucks
rawset(_G ,"_SameFrameBtnCheck", function(p)
	if p.buttonheld == nil then p.buttonheld = false end

	local ATTACK = p.cmd.buttons & BT_ATTACK
		
	if(p.buttonheld == false) then
		if(ATTACK) then 
			p.buttonheld = true
			return true
		end
	else
		if(not ATTACK) then
			p.buttonheld = false
			return nil
		end
	end
end)