-- Star Wars Empire at War: Secrets of a Fallen Empire
-- Lua Script: //Scripts/GameObject/ObjectScript_Minefield.lua
-- Authors: Galyana and Nikomer
-- Updated: 29 October, 2023

require("PGStateMachine")

function Definitions()
	DebugMessage("%s -- In definitions", tostring(Script))
	ServiceRate = 1

	Define_State("State_Init", State_Init);
	Define_State("State_Idle", State_Idle);
	
	ability_range = 300
	destruct_ability = "SELF_DESTRUCT"
	stealth_ability = "STEALTH"
	timer = 0
end

function State_Init(message)
	if message == OnEnter then

		-- prevent this from doing anything in galactic mode
		if Get_Game_Mode() ~= "Space" then
			ScriptExit()
		end
		
		if Object.Get_Owner().Is_Human() then
			Register_Prox(Object, Unit_Prox, ability_range)
			Set_Next_State("State_Idle")
		else
			Register_Prox(Object, AI_Unit_Prox, ability_range)
			Set_Next_State("State_Idle")
		end
	end
end

function State_Idle(message)
	if message == OnUpdate then
		if timer == 0 then
			timer = 7000
			DebugMessage("%s -- Re-stealth", tostring(Script))
			Object.Reset_Ability_Counter()
		else
			timer = timer - 1
		end
		if Object.Has_Ability(stealth_ability) then
			if not Object.Is_Ability_Active(stealth_ability) then
				DebugMessage("%s -- Forcing stealth", tostring(Script))
				Object.Reset_Ability_Counter()
				Object.Activate_Ability(stealth_ability, true)
			end
		end
	end
end

-- If an enemy enters the prox, self destruct
function Unit_Prox(self_obj, trigger_obj)
	if not trigger_obj.Get_Owner().Is_Enemy(Object.Get_Owner()) then
		return
	end

	-- do not trigger unless autofire is enabled
	if Object.Is_Ability_Autofire(destruct_ability) then
		if not Object.Is_Ability_Active(destruct_ability) then
			DebugMessage("%s -- BOOM!", tostring(Script))
			Object.Activate_Ability(destruct_ability, true)
		end
	end
end

-- If an enemy enters the prox, self destruct
function AI_Unit_Prox(self_obj, trigger_obj)
	if not trigger_obj.Get_Owner().Is_Enemy(Object.Get_Owner()) then
		return
	end

	-- AI does not use ability autofire
	if not Object.Is_Ability_Active(destruct_ability) then
		DebugMessage("%s -- BOOM!", tostring(Script))
		Object.Activate_Ability(destruct_ability, true)
	end
end