if game.GetMap() ~= "ttt_sabiru" then return end

local function InitEntities() 
	if !SERVER then return end
	
	if (engine.ActiveGamemode() == "terrortown") then 
		for i, v in ipairs(ents.FindByClass("npc_zombie")) do 
			v:SetModel([[models/sabiru_monsters/denizen.mdl]]) 
			if (string.StartsWith(v:GetName(), "denizen_sniper")) then
				v:SetModel([[models/sabiru_monsters/denizen_army.mdl]]) 
			end
			v:SetHealth(120) 
			v:SetMaxHealth(120) 
			v:SetBloodColor(0) 
			v:SetLagCompensated(true) 
		end
	else
		for i, v in ipairs(ents.FindByClass("npc_zombie")) do 
			v:SetModel([[models/sabiru_monsters/denizen.mdl]]) 
			if (string.StartsWith(v:GetName(), "denizen_sniper")) then
				v:SetModel([[models/sabiru_monsters/denizen_army.mdl]]) 
			end
			v:SetHealth(70) 
			v:SetMaxHealth(70) 
			v:SetBloodColor(0) 
			v:SetLagCompensated(true) 
		end
	end
end

hook.Add( "InitPostEntity", "SabiruDenizenInit", function()
	InitEntities()
end )

hook.Add( "PostCleanupMap", "SabiruDenizenInit", function()
	InitEntities()
end )

--Handling denizen dmg
hook.Add("EntityTakeDamage", "DenizenDmgHandler", function(target, dmg)
	local attacker = dmg:GetAttacker()
	
	if attacker:GetClass() == "npc_zombie" then 
		target:EmitSound("NPC_Sabiru.Hit") 
	end	
	
	if target:GetClass() != "npc_zombie" then return end

	--Since they're technically npc_zombie entities, we must set dmg type to nevergib
	--or else they'll revert back to their zombie model on death
	dmg:SetDamageType(DMG_NEVERGIB)

	--Denizen becomes hostile only to attacker
	if (attacker:IsPlayer()) and (target:Disposition(attacker) == D_LI) then
		target:AddEntityRelationship(attacker, D_HT, 99)
		target:UpdateEnemyMemory(attacker, attacker:GetPos())
		target:EmitSound("NPC_Denizen.Pain")
	end
	
	--Pain sounds
	if (attacker:IsPlayer()) and (target:Disposition(attacker) != D_LI) then
		local rng = math.random(1,10)
		if (rng > 8) then
			target:EmitSound("NPC_Denizen.Pain")
		end
	end
end)

hook.Add( "OnNPCKilled", "DenizenDeathHandler", function( npc, attacker, inflictor )
	if npc:GetClass() != "npc_zombie" then return end
	npc:EmitSound("NPC_Denizen.Scream")
end)

--Replace zombies when spawned via the spawnmenu
hook.Add("PlayerSpawnedNPC", "SabiruDenizenReplacer", function(ply, ent)
	if ent:GetClass() != "npc_zombie" then return end
	if (!IsValid(ent)) then return end
	
	local tr = util.TraceLine( {
		start = ply:EyePos(),
		endpos = ply:EyePos() + ply:EyeAngles():Forward() * 10000,
		filter = ply
	} )


	ent:SetModel("models/sabiru_monsters/denizen.mdl") 
	ent:SetHealth(100) 
	ent:SetMaxHealth(100) 
	ent:SetBloodColor(0)
	ent:SetPos(Vector (tr.HitPos.x, tr.HitPos.y, tr.HitPos.z + 10))
end)
