--[[
actor.Type : gives identifier of actor
	- Construction yard:
		- "mcv" when not deployed
		- "fact" when deployed

Media.DisplayMessage(message) : DisplayMessage for all players in chat
]]  

allPlayers = Player.GetPlayers(function(Player) 
	return not Player.HasNoRequiredUnits()
end)

local getPlayerActors = function(Player)
	return Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(Actor) return Actor.Owner == Player end)
end

local killActors = function (killed)

	clearAllTags()

	local AllActors = getPlayerActors(killed.Owner)
	for _, actor in ipairs(AllActors) do
		actor.Destroy()
	end

	Trigger.AfterDelay(1, retagMcvs)

end

local reasignActors = function (killed, killer) -- we need to get the owner of both
	clearAllTags()

	local AllActors = getPlayerActors(killed.Owner)
	for _, actor in ipairs(AllActors) do
		actor.Owner = killer.Owner
	end

	Trigger.AfterDelay(1, retagMcvs)
end


local isContained = function (element, table)
	for _, value in ipairs(table) do
		if element == value then
			return true
		end
	end
	return false
end

isMcv =function (actor)
	if actor.Type == "mcv" or actor.Type == "fact" then
		return true
	end
	return false
end

mcvProductionTrigger = function (_, actor)
	if isMcv(actor) then
		Trigger.OnKilled(actor, capturedFunc)
		Trigger.OnRemovedFromWorld(actor, tagAllMcvs)
	end
end

retagMcvs = function ()
	local AllMcvs = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, isMcv)
	for _, actor in ipairs(AllMcvs) do
		Trigger.OnKilled(actor, capturedFunc)
		Trigger.OnRemovedFromWorld(actor, tagAllMcvs)
	end
end

clearAllTags = function ()
	local AllMcvs = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, isMcv)
	for _, actor in ipairs(AllMcvs) do
				Trigger.ClearAll(actor)
	end
end

tagAllMcvs = function ()
	clearAllTags()
	Trigger.AfterDelay(1, retagMcvs)
end

WorldLoaded = function() -- This will run once when the world is loaded
	-- Gets menu option and sets if soldiers are retained after defeat
	--[[
	if Map.LobbyOption("isdestroyed") == "retain" then
		capturedFunc = reasignActors
	elseif Map.LobbyOption("isdestroyed") == "kill" then
		capturedFunc = killActors
	end
	--]]
	capturedFunc = reasignActors

	if true then
		Trigger.AfterDelay(25, tagAllMcvs)
		Trigger.OnAnyProduction(mcvProductionTrigger)
	end
end


Tick = function() -- This will run every tick

end
