
local player = player
local Color = Color
local table = table
local TEAM_UNASSIGNED	=	TEAM_UNASSIGNED
local TEAM_SPECTATOR	=	TEAM_SPECTATOR
local SERVER = SERVER
local CLIENT = CLIENT
local pairs = pairs
local string = string
local gmod = gmod

module("team")

local TeamInfo = {}
local DefaultColor = Color(255, 255, 100, 255)

TeamInfo[TEAM_UNASSIGNED] = {Name = "Unassigned", Color = DefaultColor, Score = 0}
TeamInfo[TEAM_SPECTATOR] = {Name = "Spectator", Color = DefaultColor, Score = 0}

function SetUp( id, name, color )
	TeamInfo[id] = { Name = name, Color = color, Score = 0 }
end

function TotalDeaths(index)
	local score = 0
	for id,pl in pairs( player.GetAll() ) do
		if (pl:Team() == index) then
			score = score + pl:Deaths()
		end
	end
	return score
end

function TotalFrags(index)
	local score = 0
	for id,pl in pairs( player.GetAll() ) do
		if (pl:Team() == index) then
			score = score + pl:Frags()
		end
	end
	return score
end

function NumPlayers(index)
	return #GetPlayers(index)
end

function GetPlayers(index)
	local TeamPlayers = {}
	
	for id,pl in pairs( player.GetAll() ) do
		if (pl:Team() == index) then
			table.insert(TeamPlayers, pl)
		end
	end
	
	return TeamPlayers
end

function GetScore(index)
	if (not TeamInfo[index]) then
		return 0
	end

	return TeamInfo[index].Score
end

function GetName( index )
	if (not TeamInfo[index]) then
		return ""
	end
	
	return TeamInfo[index].Name
end

function GetColor( index )

	if (not TeamInfo[index]) then
		return DefaultColor
	end
	
	return TeamInfo[index].Color
end

function SetScore(index, score)
	if (not TeamInfo[index]) then
		return
	end

	TeamInfo[index].Score = score
		
	if (SERVER) then
		local command = string.format("team.SetScore(%d, %d)", index, TeamInfo[index].Score)
		gmod.BroadcastLua( command ) 
	end
end

function AddScore(index, score)
	if (not TeamInfo[index]) then
		return
	end

	TeamInfo[index].Score = TeamInfo[index].Score + score
		
	if (SERVER) then
		local command = string.format("team.SetScore(%d, %d)", index, TeamInfo[index].Score)
		gmod.BroadcastLua( command ) 
	end
end

function SetName( index, name )
	if (not TeamInfo[index]) then
		TeamInfo[index] = {}
		TeamInfo[index].Color = DefaultColor
	end
	
	TeamInfo[index].Name = name
	
	if (SERVER) then
		local command = string.format("team.SetName(%d, %q)", index, name)
		gmod.BroadcastLua( command ) 
	end
end

function SetColor( index, color )
	if (not TeamInfo[index]) then
		TeamInfo[index] = {}
		TeamInfo[index].Name = "Team " .. index
	end
	
	TeamInfo[index].Color = color

	if (SERVER) then
		local command = string.format("team.SetColor(%d, Color(%d,%d,%d,%d))", index, color.r, color.g, color.b, color.a)
		gmod.BroadcastLua( command ) 
	end
end
