-- functions


local function CreateSquad(name)
	local squad		= script.Squad:Clone()
		squad.Name			= name and name or HttpService:GenerateGUID(false)
		squad.Queue.Value	= "Solo"
		squad.Fill.Value	= false
		squad.Parent		= SQUADS
		
	return squad
end

local function GetSquad(player)
	for _, squad in pairs(SQUADS:GetChildren()) do
		if squad.Players:FindFirstChild(player.Name) then
			return squad
		end
	end
end

local function RemovePlayer(player)
	for _, squad in pairs(SQUADS:GetChildren()) do
		local playerValue	= squad.Players:FindFirstChild(player.Name)
		
		if playerValue then
			playerValue:Destroy()
			
			if #squad.Players:GetChildren() == 0 then
				squad:Destroy()
			else
				if not squad.Players:FindFirstChild(squad.Leader.Value) then
					squad.Leader.Value	= squad.Players:GetChildren()[1].Name
				end
			end
			
			break
		end
	end
end

local function AddPlayerToSquad(player, squad)
	local currentSquad	= GetSquad(player)
	
	if currentSquad then
		RemovePlayer(player)
	end
	
	local playerValue	= Instance.new("BoolValue")
		playerValue.Name	= player.Name
		playerValue.Value	= false
		playerValue.Parent	= squad.Players
		
	if #squad.Players:GetChildren() == 1 then
		squad.Leader.Value	= player.Name
	elseif #squad.Players:GetChildren() > 1 then
		squad.Queue.Value	= "Squad"
	end
end

local function LeaveSquad(player)
	local squad	= CreateSquad()
	AddPlayerToSquad(player, squad)
	
	REMOTES.MatchInfo:FireClient(player, "Leave")
end
