-- Star Wars Empire at War: Secrets of a Fallen Empire
-- Lua Script: //Scripts/GameObject/ObjectScript_T6A.lua
-- Author: Galyana
-- Updated: 2 January, 2024

require("PGStateMachine")
require("PGBase")

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)

	ability_name = "POWER_TO_WEAPONS"
	unit_trigger_number = 1
	threat_trigger_number = 50
	targeting_range = 300	
end

function State_Init(message)
	if message == OnEnter then

		-- prevent this from doing anything in galactic mode
		if Get_Game_Mode() ~= "Land" then
			ScriptExit()
		end
		
		-- Register a proximity around the unit
		Register_Prox(Object, Unit_Prox, targeting_range)
		
		nearby_unit_count = 0
		nearby_unit_threat = 0
		recent_enemy_units = {}
		
		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 == OnUpdate then
		if (nearby_unit_count >= unit_trigger_number and nearby_unit_threat >= threat_trigger_number) then
			Object.Activate_Ability(ability_name, true)
		else
			Object.Activate_Ability(ability_name, false)	
		end

		-- reset tracked units each service.
		nearby_unit_count = 0
		nearby_unit_threat = 0
		recent_enemy_units = {}

		--Land units can change hands
		if Object.Get_Owner().Is_Human() then
			Set_Next_State("State_Human_No_Autofire")
		end
	end
end

function State_Human_No_Autofire(message)
	if message == OnUpdate then

		--Land units can change hands
		if Object.Get_Owner().Is_Human() then
			Sleep(1)
		else
			Set_Next_State("State_AI_Autofire")
		end
	end
end

-- If any enemy vehicle enters the prox, anchor to increase damage and shield regen
function Unit_Prox(self_obj, trigger_obj)
	if not trigger_obj.Is_Category("Vehicle") then
		return
	end
	
	if not trigger_obj.Get_Owner().Is_Enemy(Object.Get_Owner()) then
		return
	end
	
	-- If we haven't seen this unit recently, track him
	if recent_enemy_units[trigger_obj] == nil then
		recent_enemy_units[trigger_obj] = trigger_obj
		nearby_unit_count = nearby_unit_count + 1
		nearby_unit_threat = nearby_unit_threat + trigger_obj.Get_Type().Get_Combat_Rating()
	end	
end