wormDelay = nil
testCondition = true
botPlayers = {}
IsAnyBotsHere = false
currentConyards = {}
CheckPlayerTechtree = false
PlayersThatNotchoosedyet = 0
FactionsMode = 0
SubfactionPrerequisitesList = {}
SubfactionPrerequisitesList["atreides"] = "subfaction.atreides"
SubfactionPrerequisitesList["fremen"] = "subfaction.fremen"
SubfactionPrerequisitesList["harkonnen"] = "subfaction.harkonnen"
SubfactionPrerequisitesList["corrino"] = "subfaction.corrino"
SubfactionPrerequisitesList["ordos"] = "subfaction.ordos"
SubfactionPrerequisitesList["smuggler"] = "subfaction.smuggler"
SubfactionPrerequisitesList["mercenary"] = "subfaction.mercenary"
Mergedsubfactions = { "merged.fremen","merged.corrino","merged.smuggler", "merged.mercenary"}
WorldLoaded = function()
	--get players
	mp0=Player.GetPlayer("Multi0")
	mp1=Player.GetPlayer("Multi1")
	mp2=Player.GetPlayer("Multi2")
	mp3=Player.GetPlayer("Multi3")
	mp4=Player.GetPlayer("Multi4")
	mp5=Player.GetPlayer("Multi5")
	mp6=Player.GetPlayer("Multi6")
	mp7=Player.GetPlayer("Multi7")
	mp8=Player.GetPlayer("Multi8")
	mp9=Player.GetPlayer("Multi9")
	mp10=Player.GetPlayer("Multi10")
	mp11=Player.GetPlayer("Multi11")
	mp12=Player.GetPlayer("Multi12")
	mp13=Player.GetPlayer("Multi13")
	mp14=Player.GetPlayer("Multi14")
	mp15=Player.GetPlayer("Multi15")
	mp16=Player.GetPlayer("Multi16")
	mp17=Player.GetPlayer("Multi17")
	mp18=Player.GetPlayer("Multi18")
	mp19=Player.GetPlayer("Multi19")
	mp20=Player.GetPlayer("Multi20")
	mp21=Player.GetPlayer("Multi21")
	mp22=Player.GetPlayer("Multi22")
	mp23=Player.GetPlayer("Multi23")
	mp24=Player.GetPlayer("Multi24")
	mp25=Player.GetPlayer("Multi25")
	mp26=Player.GetPlayer("Multi26")
	mp27=Player.GetPlayer("Multi27")
	Players = {mp0, mp1, mp2, mp3, mp4, mp5, mp6, mp7, mp8, mp9, mp10, mp11, mp12, mp13, mp14, mp15, mp16, mp17, mp18, mp19, mp20, mp21, mp22, mp23, mp24, mp25, mp26, mp27}
	FactionsMode  = tonumber(Map.LobbyOption("fation_mode"))
	if (FactionsMode == 0) then
		--Media.DisplayMessage("you play with standart d2k mode", "Mentat", HSLColor.DarkRed)
	end
	if (FactionsMode == 1) then
		Media.DisplayMessage("Sub-faction Mode - Choose between Major faction or one of its sub-factions", "Mentat",  HSLColor.DarkRed)
	end
	if (FactionsMode == 2) then
		Media.DisplayMessage("Merged Faction mode - chosen will be merged to your Major faction","Mentat", HSLColor.DarkRed)
	end
	for i, player in pairs(Players)
		do
		-- freecarryall section
		if player.HasPrerequisites({"FreeCarry"})
		then
			addCarryToPlayer(player)
		end
		-- factions  options check
		if (FactionsMode == 0)
		then
			player.GrantCondition("vanilla_factions_Only")
			addmcv(player)
		elseif (FactionsMode == 1) then
			CheckPlayerTechtree = true
			player.GrantCondition("subfactions")
			botsubfaction(player)
		elseif (FactionsMode == 2) then
			player.GrantCondition("mergedsubfactions")
			botsubfaction(player)
			CheckPlayerTechtree = true
		end
		--adding bots to table
		if player.IsBot
		then
			table.insert(botPlayers, player)
		end
	end
	-- worm delay section
	wormDelay = Map.LobbyOption("WormsSpawnDelay")
	if tonumber(wormDelay) > 0
	then
		delay = tonumber(Map.LobbyOption("WormsSpawnDelay"))
		Trigger.AfterDelay(DateTime.Minutes(delay), function()
			--in teory any player can own wormspawner actor
			wormSpawnFunction(Player.GetPlayer("Creeps"))
			wormSpawnFunction(Player.GetPlayer("Neutral"))
			for i, player in pairs(Players)
			do
				wormSpawnFunction(player)
			end
		end)
	end
-- testing bots locations:
	for i, bot in pairs(botPlayers)
	do
		IsAnyBotsHere = true
	end
end

Tick = function()
-- check if player already choose subfaction
if(CheckPlayerTechtree == true and PlayersThatNotchoosedyet > 0) then
--	Media.DisplayMessage("cheking")
	techtreecheck()
end


	-- Bot capture protection scripts: executed every 2 sec,testing new Bots Conyards executed every 5 sec
  if IsAnyBotsHere then
    if DateTime.GameTime % DateTime.Seconds(5) == 0
    then
      findConyards()
    end
    if DateTime.GameTime % DateTime.Seconds(2) == 0 then
      engiProtection()
    end
  end
end

function addmcv(player)
	local actors = player.GetActorsByType("choosefaction")
	for pom, actor in pairs(actors) do
		Actor.Create("mcv", true, { Owner = player, Facing = Angle.SouthWest, Location = actor.Location})
		actor.Kill();
	end
end

function techtreecheck()
	for i, player in pairs(Players) do
		local actors = player.GetActorsByType("choosefaction")
		if FactionsMode == 1 then
			for faction, prerequisite in pairs(SubfactionPrerequisitesList) do
				if player.HasPrerequisites({prerequisite}) then
					for pom, actor in pairs(actors) do
						Actor.Create("mcv", true, { Owner = player, Facing = Angle.North, Location = actor.Location, Faction = faction})
						actor.Kill();
						PlayersThatNotchoosedyet = PlayersThatNotchoosedyet - 1
						--Media.DisplayMessage("Subfaction choosed", tostring(PlayersThatNotchoosedyet))
					end
				end
			end
		elseif FactionsMode == 2 then
			for faction, prerequisite in pairs(Mergedsubfactions) do
				if player.HasPrerequisites({prerequisite}) then
					for pom, actor in pairs(actors) do
						Actor.Create("mcv", true, { Owner = player, Facing = Angle.North, Location = actor.Location, Faction = player.Faction})
						actor.Kill();
						PlayersThatNotchoosedyet = PlayersThatNotchoosedyet - 1
						--Media.DisplayMessage("Subfaction choosed Remaining"..tostring(PlayersThatNotchoosedyet))
					end
				end
			end
		end
	end
end

function botsubfaction(player)
	if(not player.IsBot)
	then
		PlayersThatNotchoosedyet = PlayersThatNotchoosedyet + 1
		--Media.DisplayMessage("got the player",tostring(PlayersThatNotchoosedyet) )
	else
		local bluefactions = {"atreides", "fremen"}
		local redfactions = {"harkonnen", "corrino"}
		local greenfactions = {"ordos", "smuggler", "mercenary"}
		local faction = {}
		local actors = player.GetActorsByType("choosefaction")
		if (FactionsMode == 1) then
			if player.Faction == "atreides" then
				faction = bluefactions
			end
			if player.Faction == "harkonnen" then
				faction = redfactions
			end
			if player.Faction == "ordos" then
				faction = greenfactions
			end
			--Media.DisplayMessage("got the bot")
			for pom, actor in pairs(actors) do
				Actor.Create("mcv", true, { Owner = player, Facing = Angle.North, Location = actor.Location, Faction = Utils.Random(faction)})
				actor.Kill();
			end
		else
			faction = player.Faction
			for pom, actor in pairs(actors) do
				Actor.Create("mcv", true, { Owner = player, Facing = Angle.North, Location = actor.Location, Faction = player.Faction})
				Actor.Create( Utils.Random(Mergedsubfactions), true, { Owner = player, Facing = Angle.North, Location = actor.Location, Faction = player.Faction})
				actor.Kill();
			end
		end
	end
end

function engiProtection()

  for i, conyard in pairs(currentConyards) do
    if conyard.IsDead then
        --Media.DisplayMessage("conyard dead")
    else
      actorsInRadius = Map.ActorsInCircle(conyard.CenterPosition, WDist.New(3036))
      --Media.DisplayMessage("testing")
      for _, actor in pairs(actorsInRadius) do
        if actor.Type == "engineer" then
          --Media.DisplayMessage(actor.Type)
          conyard.Sell()
          currentConyards[i] = nil
        end
      end
    end
  end
end

function addCarryToPlayer(player)
	local actors = player.GetActorsByTypes({"mcv", "construction_yard", "choosefaction"})
	local hasCarry = false
	for i, actor in pairs(actors)
	do
		if (actor.Type == "mcv") or (actor.Type == "construction_yard") or (actor.Type == "choosefaction")
		then
			--case then player have multiplye conyards from start
			if (not hasCarry )
			then
			Reinforcements.Reinforce(player, { "carryall" }, { actor.Location }, 10)
			hasCarry = true
			end
		end
	end
end

function wormSpawnFunction(owner)
    local actorsSpawner = owner.GetActorsByType("wormspawner")
  if actorsSpawner ~= nil
  then
    for i, spawner in pairs(actorsSpawner)
    do
      if spawner.AcceptsCondition("WormSpamDelayed")
      then
        spawner.GrantCondition("WormSpamDelayed")
      end
    end
  end
end

function findConyards()
  local newConyards = {}
  local newLocations = {}
 for i, bot in pairs(botPlayers)
  do
    conyards = bot.GetActorsByType("construction_yard")
    for _, conyard in pairs(conyards) do
      table.insert(newConyards, conyard)
      --Media.DisplayMessage("adding",conyard.Type)
      --table.insert(newLocations, conyard.Location)
    end
  end
  currentConyards = newConyards
end
