CollabVMDesktopClient/CollabVMClient/ViewModels/ServerListViewModel.cs

85 lines
2.6 KiB
C#
Raw Normal View History

2023-08-29 08:52:35 -04:00
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Media.Imaging;
using CollabVMClient.Views;
using MsBox.Avalonia;
namespace CollabVMClient.ViewModels
{
internal class ServerListViewModel : ViewModelBase
{
private IConfig config;
private CancellationTokenSource populateListCt;
public string ServerListHeader => "Servers";
public ObservableCollection<CVMNodeViewModel> Nodes { get; } = new ObservableCollection<CVMNodeViewModel>();
public ServerListViewModel(IConfig config)
{
this.config = config;
populateListCt = new();
PopulateList(config.Nodes, populateListCt.Token);
}
public async Task PopulateList(string[] urls, CancellationToken token)
{
foreach (var url in urls)
{
if (token.IsCancellationRequested) return;
await Multicollab(url, token);
}
}
public async Task Multicollab(string url, CancellationToken token)
{
CVMNodeViewModel[] nodes;
try
{
nodes = await Utilities.GetNodes(url);
} catch (Exception e)
{
await MessageBoxManager.GetMessageBoxStandard("CollabVM Connection Error", $"Failed to connect to the CollabVM Server at {url}:\n{e.Message}", MsBox.Avalonia.Enums.ButtonEnum.Ok, MsBox.Avalonia.Enums.Icon.Error).ShowAsync();
return;
}
foreach (var node in nodes)
{
if (token.IsCancellationRequested) return;
Nodes.Add(node);
var newNodes = Nodes.OrderBy(n => n.ID).ToArray();
Nodes.Clear();
foreach (CVMNodeViewModel m in newNodes)
{
Nodes.Add(m);
}
}
}
public void RefreshList()
{
populateListCt.Cancel();
populateListCt = new();
Nodes.Clear();
PopulateList(config.Nodes, populateListCt.Token);
}
public bool CanRefreshList() => true;
public async void AddServer(object parent)
{
var win = new AddServer();
await win.ShowDialog((Window)parent);
if (win.URL != null) Multicollab(win.URL, populateListCt.Token);
}
public bool CanAddServer() => true;
}
}