-- Star Wars Empire at War: Secrets of a Fallen Empire
-- Lua Script: //Scripts/GameObject/ObjectScript_Tractor_Satellite.lua
-- Author: Galyana
-- Updated: 29 January, 2026

--Allows the tractor beam satellite to function for ai players
--Also allows autofire to work for human players

require("PGStateMachine")

function Definitions()
	ServiceRate = 1

	Define_State("State_Init", State_Init);
	Define_State("State_AI_Autofire", State_AI_Autofire)
	Define_State("State_Human_No_Autofire", State_Human_No_Autofire)
	Define_State("State_Human_Autofire", State_Human_Autofire)

	ability_name = "TRACTOR_BEAM"
	-- Satellite tractor range is 2000, let the target get closer so they don't immediately fly away
	-- Satellite vision range is 1350, it can target units the player cannot see
	-- ability_range = 1500

	stealth_ability = "STEALTH"
end

function State_Init(message)
	if message == OnEnter then
		-- prevent this from doing anything in galactic mode
		if Get_Game_Mode() == "Galactic" then
			ScriptExit()
		end

		if Object.Get_Owner().Is_Human() then
			Set_Next_State("State_Human_No_Autofire")
		else
			Set_Next_State("State_AI_Autofire")
		end
	end
end

function State_AI_Autofire(message)
	if message == OnEnter then
		Register_Prox(Object, Unit_Prox, 1500) -- Give the AI player a longer range
	end

	if message == OnUpdate then
		--This satellite can be captured by a Hutt player
		if Object.Get_Owner().Is_Human() then
			Set_Next_State("State_Human_No_Autofire")
		end
	end
end

function State_Human_No_Autofire(message)
	-- Turn off prox check if autofire is disabled
	if message == OnEnter then
		Object.Cancel_Event_Object_In_Range(Unit_Prox)
	end

	if message == OnUpdate then
		if Object.Is_Ability_Autofire(ability_name) then
			Set_Next_State("State_Human_Autofire")
		end
	end
end

function State_Human_Autofire(message)
	if message == OnEnter then
		Register_Prox(Object, Unit_Prox, 1000)
	end

	if message == OnUpdate then
		if Object.Is_Ability_Autofire(ability_name) then
			return
		else
			Set_Next_State("State_Human_No_Autofire")
		end

	end
end

-- Tractor beam first target that enters range
function Unit_Prox(self_obj, trigger_obj)
	if not trigger_obj.Get_Owner().Is_Enemy(Object.Get_Owner()) then
		return
	end
	
	-- ignore stealthed enemies
	if trigger_obj.Is_Ability_Active(stealth_ability) then
		return
	end

	-- prevent multiple tractor beams hitting one target
	if trigger_obj.Is_Under_Effects_Of_Ability(ability_name) then
		return
	end

	-- hold enemy until it dies or escapes
	if Object.Is_Ability_Active(ability_name) then
		return
	end

	if trigger_obj.Get_Owner().Is_Enemy(Object.Get_Owner()) then
		if trigger_obj.Is_Category("Transport | Corvette | Frigate | SpaceHero") then
			Object.Activate_Ability(ability_name, trigger_obj)
		end
	end
end