-- Extra Enemy Health System v1.0
-- Made by Garrean

-- Add as much health to the enemy as is specified in the 10th UDMF argument
local function addExtraHealth(mo)
	if mo.spawnpoint.args[9] > 0 then
		mo.health = $ + mo.spawnpoint.args[9]
		mo.ehstarthealth = mo.health 
		mo.ehfuse = 0
	end
end

-- Function to deal with enemies with extra health
local function handleExtraHealth(target, inflictor, source, damage, damagetype)
	if not (target and target.valid and target.ehstarthealth) then return end -- If it had extra health
	if target.ehfuse > 0 then return true end -- Can't hurt an enemy when flashing!
	if target.health <= 1 then return false end -- Only if the target has extra health!
	
	-- If a player is the one doing the damage
	if source and source.player and source.player.valid then
	
		-- Nuke is an insta-kill!
		if damagetype == DMG_NUKE then
			target.health = 1
			return false
		end
	
		-- If the target isn't currently damaged
		if target.ehfuse == 0 then
			S_StartSound(target, sfx_dmpain)
			target.ehfuse = TICRATE
			target.health = $ - 1
		end
		
		-- Reverse the player's momentum if they hit it (not with a nuke)
		if source == inflictor and damagetype != DMG_NUKE then
			source.momx = $ * -1
			source.momy = $ * -1
		end
		
	end
	
	return true -- Override normal functionality
end

-- Make the enemy flash when damaged
local function flashDamagedEnemies(mo)
	if mo and mo.valid and mo.ehstarthealth and mo.ehfuse > 0 then
		if mo.ehfuse % 2 == 0 then
			mo.flags2 = $ | MF2_DONTDRAW
		else
			mo.flags2 = $ & ~MF2_DONTDRAW
		end
	end
end

-- Make sure the enemy can't be touched when flashing
local function intangibleWhenFlashing(special, toucher)
    if toucher and toucher.player and toucher.player.valid then
		if special and special.valid and special.ehstarthealth then
			if special.ehfuse > 0 then return true end
        end
    end
end

-- Decrement fuse every tic until it reaches zero
local function decrementFlashFuse(mo)
	if mo and mo.valid and mo.ehstarthealth then
		if mo.ehfuse > 0 then mo.ehfuse = $ - 1 end
	end
end

-- Add hooks for each function for enemies only
for i = 0, #mobjinfo - 1 do
    if mobjinfo[i] and (mobjinfo[i].flags & MF_ENEMY) then
		addHook("MapThingSpawn", addExtraHealth, i)
		addHook("MobjDamage", handleExtraHealth, i)
		addHook("MobjThinker", flashDamagedEnemies, i)
		addHook("TouchSpecial", intangibleWhenFlashing, i)
		addHook("MobjThinker", decrementFlashFuse, i)
    end
end