-- Pho_Lines.levelgen
-- Pho_Lines.levelgen
function setAllLines(teamIndex)
	for _, zoneJunk in ipairs(zoneData) do
		for _, line in ipairs(zoneJunk["lines"]) do
			line:setTeam(teamIndex)
		end
	end
end


function updateLines()
	for _, zoneJunk in ipairs(zoneData) do
		local lines = zoneJunk["lines"]
		local zoneTeam = zoneJunk["zone"]:getTeamIndex()
		
		-- If the zone's team is different than its lineitems, we need to
		-- update the lineitems
		if zoneTeam ~= lines[1]:getTeamIndex() then
			for _, line in ipairs(lines) do
				line:setTeam(zoneTeam)
			end
		end
	end
end


function onScoreChanged(scoreChange, teamIndex, player)
	local game = bf:getGameInfo()
	local team = game:getTeam(teamIndex)
	local teamScore = team:getScore()

	-- If we've made a touchdown, change everything back to neutral team
	if teamScore % zoneCount == 0 and scoreChange > 0 then
		setAllLines(Team.Neutral)

	-- Else update the line artwork to reflect the proper teams
	else
		-- We have to delay the update one tick because the zones don't seem to
		-- reflect the correct teams when this even is fired.  Bug?
		Timer:scheduleOnce(updateLines, 1)  -- 1 ms is all that's needed
	end
end


function main()
	bf:subscribe(Event.ScoreChanged)
	
	-- Globals
	-- How many zones we have
	zoneCount = 10
	
	-- Load up all of our zoneData into a complex object for fast lookup later
	zoneData = {}
	
	-- Each of the indexes correspond to a goalzone ID. The members:
	--    zone  - the zone object itself
	--    lines - the lineitem objects that will change team when the zone changes
	--            team
	zoneData = 
	{
		{
			["zone"] = bf:findObjectById(11),
			["lines"] = {
				bf:findObjectById(1),
			}
		},
		{
			["zone"] = bf:findObjectById(12),
			["lines"] = {
				bf:findObjectById(2),
			}
		},
		{
			["zone"] = bf:findObjectById(13),
			["lines"] = {
				bf:findObjectById(3),
			}
		},
		{
			["zone"] = bf:findObjectById(14),
			["lines"] = {
				bf:findObjectById(4),
			}
		},
		{
			["zone"] = bf:findObjectById(15),
			["lines"] = {
				bf:findObjectById(5),
			}
		},
		{
			["zone"] = bf:findObjectById(16),
			["lines"] = {
				bf:findObjectById(6),
			}
		},
		{
			["zone"] = bf:findObjectById(17),
			["lines"] = {
				bf:findObjectById(7),
			}
		},
		{
			["zone"] = bf:findObjectById(18),
			["lines"] = {
				bf:findObjectById(8),
			}
		},
		{
			["zone"] = bf:findObjectById(19),
			["lines"] = {
				bf:findObjectById(9),
			}
		},
		{
			["zone"] = bf:findObjectById(20),
			["lines"] = {
				bf:findObjectById(10),
			}
		}
	}
end