--------------------------------------------------------------------------------
--
--   Stinger Functions
--
--------------------------------------------------------------------------------

-- These functions make it very easy to set up 'stingers' - bits of speech that
-- trigger when you approach an area. 

STINGER_EVENT    = 1
STINGER_FUNCTION = 2

--? @group Stinger

-- this is the table that keeps all of the stingers
_StingerList = {}


--? @shortdesc Add a stinger to trigger at a specific location
--? @extdesc You must remember to set Stinger_Manager going as a rule with a regular interval
--? @args PlayerID player, MarkerID marker, EVENT eventname
function Stinger_AddEvent(playerid, markerid, eventname)

	-- add this stinger to the table
	table.insert(_StingerList, {player = playerid, location = markerid, event = eventname, stingertype = STINGER_EVENT})

end

--? @shortdesc Add a stinger to trigger at a specific location
--? @extdesc You must remember to set Stinger_Manager going as a rule with a regular interval
--? @args PlayerID player, MarkerID marker, LuaFunction functionname
function Stinger_AddFunction(playerid, markerid, functionname)

	-- add this stinger to the table
	table.insert(_StingerList, {player = playerid, location = markerid, event = functionname, stingertype = STINGER_FUNCTION})

end

--? @shortdesc Remove all stingers triggered from a specific location
--? @args PlayerID player, MarkerID marker
function Stinger_Remove(playerid, markerid)

	-- for every item in the table
	for n = table.getn(_StingerList), 1, -1 do
		
		-- if this stinger is triggered by the given location
		if (_StingerList[n].player == playerid) and (_StingerList[n].location == markerid) then
			
			-- remove the stinger
			table.remove(_StingerList, n)
			
		end
		
	end
	
end


-- this is the rule that checks the stingers during the mission
function Stinger_Manager()

	-- only run if no event is currently happening
	if (Event_IsAnyRunning() == false) then
		
		local stingermanagerdone = false
		
		-- for every item in the table
		for n = table.getn(_StingerList), 1, -1 do
			
			-- if one's been triggered... no more for now
			if (stingermanagerdone == false) then
				
				local markerpos = Marker_GetPosition(_StingerList[n].location)
				local camerapos = Camera_GetTargetPos()
				
				-- first check the camera is looking at the area
				if (World_DistancePointToPoint(markerpos, camerapos) < 20) then
					
					-- now check there are people close to the marker
					if Player_AreSquadsNearMarker(_StingerList[n].player, _StingerList[n].location) then
						
						-- activate and then remove the stinger
						if (_StingerList[n].stingertype == STINGER_EVENT) then
							Util_StartIntel(_StingerList[n].event)
						elseif (_StingerList[n].stingertype == STINGER_FUNCTION) then
							_StingerList[n].event()
						end
						
						table.remove(_StingerList, n)
						stingermanagerdone = true
						
					end
				end
			end
		end
	end
end

