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

local function fixnetusage()
    for _, ent in ipairs(ents.FindByClass"phys_bone_follower") do
        local owner = ent:GetOwner()

        if IsValid(owner) and owner:GetModel() == "models/sabiru_monsters/denizen.mdl" then
            for _, ply in player.Iterator() do
               ent:SetPreventTransmit(ply, true)
            end
        end
    end
end

concommand.Add( "sabiru_bypass_plylimit", function( ply, cmd, args )
	if (!ply:IsAdmin()) then print( "Nuh uh. Not an admin." ) return end
	
	for i, ent in ipairs(ents.FindByName("area_delimiter_disable")) do
		ent:Fire("Trigger")
	end
    print( "Removed boundaries!" )
end )

--Sandbox specific code
hook.Add( "InitPostEntity", "RunSabiSandboxScript", function()
	fixnetusage()
	if (engine.ActiveGamemode() == "sandbox") then 
		for i, ent in ipairs(ents.FindByName("sandbox_values")) do
			ent:Fire("Trigger")
		end
	end
end )

hook.Add( "PostCleanupMap", "RunSabiSandboxScript2", function()
	fixnetusage()
	if (engine.ActiveGamemode() == "sandbox") then 
		for i, ent in ipairs(ents.FindByName("sandbox_values")) do
			ent:Fire("Trigger")
		end
	end
end )

--So that the boss knows where every player is at all times
--Made for both ttt and sandbox in mind
function SabUpdateEnemyMemory()
	for i, v in ipairs(player.GetAll()) do 
		if engine.ActiveGamemode() == "terrortown" then
			if !v:IsTraitor() then 
				for i, boss in ipairs(ents.FindByClass("npc_zombine")) do
					boss:UpdateEnemyMemory(v, v:GetPos())
				end		
			end
		else
			for i, boss in ipairs(ents.FindByClass("npc_zombine")) do
				boss:UpdateEnemyMemory(v, v:GetPos())
			end		
		end		
	end
end

--So that zombies still love newly spawned players
hook.Add( "PlayerSpawn", "ZombiesLikeNewPlayers", function(player, transition) 
	for i, ent in ipairs(ents.FindByClass("npc_zombie")) do
		ent:AddEntityRelationship(player, D_LI, 99)
	end
end)

if SERVER then
	util.AddNetworkString("sabiruChatPrint")
	util.AddNetworkString("openUrl")
end

if CLIENT then
	net.Receive("sabiruChatPrint", function()
		local text = net.ReadString()
		chat.PlaySound()
		chat.AddText( Color( 230, 230, 230 ), text)
	end)
	
	net.Receive("openUrl", function()
		local url = net.ReadString()
			
		--I should kill myself
		if BRANCH != "x86-64" then 
			chat.AddText(Color(230,230,230),"Opening ",Color(230,100,230),url, Color(230,230,230)," on the Steam Overlay browser")
			gui.OpenURL("https://"..url) 
			return 
		end

		local frame = vgui.Create( "DFrame" )
		frame:SetTitle( "Sabiru web browser!!!" )
		frame:SetSize( ScrW() * 0.75, ScrH() * 0.75 )
		frame:Center()
		frame:MakePopup()

		local html = vgui.Create( "DHTML", frame )
		html:Dock( FILL )
		html:OpenURL( url )
		chat.AddText(Color(230,230,230),"Opening ",Color(230,100,230),url)
	end)
end

--Begin TTT specific code
if (engine.ActiveGamemode() != "terrortown") then return end
print("Running TTT sabiru script")

local function CheckPlayerAmount(num, shouldDisplayText)
	if (player.GetCount() >= num) then 
		for i, ent in ipairs(ents.FindByName("area_delimiter_disable")) do
			ent:Fire("Trigger")
			return
		end
	end
	
	
	if (shouldDisplayText) and SERVER then
		net.Start("sabiruChatPrint")
		net.WriteString("Not enough players to unlock full playing area (minimum "..num.."). \nTo open up the map, run the sabiru_bypass_plylimit console command as an admin. Alternatively, you can toggle barriers in the admin room (outside the map)")
		net.Broadcast()
	end
end

--Round start code
hook.Add("TTTBeginRound", "SabiruRoundStart", function()
	--Unlock full playable area if there's enough players
	CheckPlayerAmount(20, false)

	--Set up relationships
	for i, ply in ipairs(player.GetAll()) do 
		if ply:IsTraitor() then 
			for i, boss in ipairs(ents.FindByName("chaser_overworld")) do
				boss:AddEntityRelationship(ply, D_LI, 99)
			end
		end
	end
	
	--Set up relationships
	for i, ply in ipairs(player.GetAll()) do 
		if ply:IsTraitor() then 
			for i, sniper in ipairs(ents.FindByClass("npc_sniper")) do
				sniper:AddEntityRelationship(ply, D_LI, 99)
			end
		end
	end
	
	--Play intro on first round
	--Up ahead is the dumbest shit ever all because gmod does not support
	--point_viewcontrol_multiplayer in 2024
	--in my testing this may cause one (1) player in the server to become invincible
	--too bad!
	if GetGlobalInt("ttt_rounds_left") != GetConVar("ttt_round_limit"):GetInt() then return end
	
	for i, ent in ipairs(ents.FindByName("first_round_relay")) do 
		ent:Fire("Trigger")
	end
		
	for i, ply in ipairs(player.GetAll()) do 
		for i, dummy in ipairs(ents.FindByName("intro_viewcontrol")) do
			local camera = ents.Create("point_viewcontrol")
			
			camera:SetPos(dummy:GetPos())
			camera:SetAngles(dummy:GetAngles())
			camera:SetKeyValue("spawnflags", 12)
			camera:Spawn()
			camera:Input("Enable", ply)

			timer.Simple(8, function()
				camera:Input("Disable", ply)
			end)
		end		
	end	
	

end)

hook.Add("TTTPrepareRound", "SabiruRoundPrep", function()
	timer.Simple(2, function()
		for i, ent in ipairs(ents.FindByName("ttt_values")) do
			ent:Fire("Trigger")
			print("Killed sandbox stuff")
		end
	end)

		
	fixnetusage()
	
	--Unlock full playable area if there's enough players
	timer.Simple(2, function()
		CheckPlayerAmount(20, true)
	end)
end)


