-- ia.levelgen
function setAllLines(teamIndex)
	for i, j in ipairs(lineSets) do
		for _, v in ipairs(lineSets[i]) do
			v:setTeam(teamIndex)
		end
	end
end


function setLineSetTeam(newTeam, oldTeam)
	for i, set in ipairs(lineSets) do
		if set[1]:getTeamIndex() == oldTeam then
			for _, v in ipairs(set) do
				v:setTeam(newTeam)
			end
			
			break
		end
	end
end


function onScoreChanged(scoreChange, teamIndex, player)
	-- If we lost a flag, set our lines to hostile team again
	if scoreChange == -1 then 
		setLineSetTeam(Team.Hostile, teamIndex)
		return
	end
	
	local game = bf:getGameInfo()
	local flags = game:getFlagCount()
	local team = game:getTeam(teamIndex)
	local teamScore = team:getScore()
	
	-- Workaround for team score being updated after event, fixed in 019a when 'getVersion'
	-- was introduced
	local touchdownCount = flags
	if getVersion == nil then
		touchdownCount = flags - 1
	end
	
	-- If we've made a touchdown, change everything to the team color
	if teamScore % flags == touchdownCount then
		setAllLines(teamIndex)
		
		lastScoreWasTouchdown = true
	else
		if lastScoreWasTouchdown then
			lastScoreWasTouchdown = false

			setAllLines(Team.Hostile)
		end
	  
		-- Set the artwork for the relevant team
		setLineSetTeam(teamIndex, Team.Hostile)
	end
end


function main()
	bf:subscribe(Event.ScoreChanged)
	
	lineTeams = {
		Team.Hostile,
		Team.Hostile,
	}
	
	-- Globals
	lastScoreWasTouchdown = false
	
	lineSets = {
		{
			bf:findObjectById(1),
			bf:findObjectById(2),
			bf:findObjectById(9),
			bf:findObjectById(10),
		},
		{
			bf:findObjectById(3),
			bf:findObjectById(4),
			bf:findObjectById(7),
			bf:findObjectById(8),
		},
		{
			bf:findObjectById(5),
			bf:findObjectById(6),
			bf:findObjectById(11),
			bf:findObjectById(12),
		},
	}
end