-- events


REMOTES.Kick.OnServerEvent:Connect(function(player, other)
	local squad	= GetSquad(other)
	
	if squad then
		if player.Name == squad.Leader.Value then
			LeaveSquad(other)
		end
	end
end)

REMOTES.SetLeader.OnServerEvent:Connect(function(player, other)
	local squad	= GetSquad(other)
	
	if squad then
		if player.Name == squad.Leader.Value then
			squad.Leader.Value	= other.Name
		end
	end
end)

REMOTES.ToggleQueue.OnServerEvent:connect(function(player)
	local squad	= GetSquad(player)
	
	if squad then
		if player.Name == squad.Leader.Value then
			if squad.Queue.Value == "Solo" then
				squad.Queue.Value	= "Squad"
			elseif squad.Queue.Value == "Squad" then
				if #squad.Players:GetChildren() <= 1 then
					squad.Queue.Value	= "Solo"
					squad.Fill.Value	= false
				end
			end
		end
	end
end)

REMOTES.ToggleFill.OnServerEvent:connect(function(player)
	local squad	= GetSquad(player)
	
	if squad then
		if player.Name == squad.Leader.Value then
			if squad.Queue.Value == "Solo" then
				squad.Fill.Value	= false
			else
				squad.Fill.Value	= not squad.Fill.Value
			end
		end
	end
end)


REMOTES.SendInvite.OnServerEvent:connect(function(from, to)
	local squad	= GetSquad(from)
	
	if squad.Leader.Value == from.Name then
		if #squad.Players:GetChildren() < MAX_SQUAD_SIZE then
			local success	= false
			pcall(function()
				response	= REMOTES.RespondToInvite:InvokeClient(to, from.Name)
			end)
			
			if response and from:IsDescendantOf(Players) then
				local squad	= GetSquad(from)
				if #squad.Players:GetChildren() < MAX_SQUAD_SIZE then
					AddPlayerToSquad(to, squad)
				end
			end
		end
	end
end)

REMOTES.Ready.OnServerEvent:connect(function(player, ready)
	local squad	= GetSquad(player)
	
	if squad then
		squad.Players[player.Name].Value	= ready
	end
end)

REMOTES.LeaveSquad.OnServerEvent:connect(function(player)
	LeaveSquad(player)
end)

Players.PlayerAdded:connect(function(player)
	local info		= player:GetJoinData()
	local squadName	= info.TeleportData
	
	PLAYER_DATA:WaitForChild(player.Name)
	
	if squadName then
		local currentSquad	= SQUADS:FindFirstChild(squadName)
		
		if currentSquad then
			if #currentSquad.Players:GetChildren() < MAX_SQUAD_SIZE then
				AddPlayerToSquad(player, currentSquad)
			else
				AddPlayerToSquad(player, CreateSquad())
			end
		else
			AddPlayerToSquad(player, CreateSquad(squadName))
		end
	else
		AddPlayerToSquad(player, CreateSquad())
	end
end)

Players.PlayerRemoving:connect(function(player)
	RemovePlayer(player)
end)
