78 lines
2.3 KiB
C#
78 lines
2.3 KiB
C#
using System.Collections.ObjectModel;
|
|
using CommunityToolkit.Mvvm.ComponentModel;
|
|
using CommunityToolkit.Mvvm.Input;
|
|
using Massenger.Client.Pages;
|
|
using Massenger.Client.Services;
|
|
using Massenger.Shared;
|
|
|
|
namespace Massenger.Client.ViewModels;
|
|
|
|
public partial class ChatsViewModel(ApiClient apiClient, RealtimeService realtimeService) : BaseViewModel
|
|
{
|
|
public ObservableCollection<ChatSummaryDto> Chats { get; } = [];
|
|
|
|
[ObservableProperty]
|
|
private ChatSummaryDto? selectedChat;
|
|
|
|
public string EmptyState => Chats.Count == 0 ? "No chats yet. Open Discover to start a dialog, group or channel." : string.Empty;
|
|
|
|
[RelayCommand]
|
|
public async Task LoadAsync()
|
|
{
|
|
await RunBusyAsync(async () =>
|
|
{
|
|
var chats = await apiClient.GetChatsAsync();
|
|
MainThread.BeginInvokeOnMainThread(() =>
|
|
{
|
|
Chats.Clear();
|
|
foreach (var chat in chats)
|
|
{
|
|
Chats.Add(chat);
|
|
}
|
|
|
|
OnPropertyChanged(nameof(EmptyState));
|
|
});
|
|
});
|
|
}
|
|
|
|
[RelayCommand]
|
|
public async Task OpenChatAsync(ChatSummaryDto? chat)
|
|
{
|
|
if (chat is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
SelectedChat = null;
|
|
await Shell.Current.GoToAsync($"{nameof(ChatPage)}?chatId={chat.Id}");
|
|
}
|
|
|
|
public void AttachRealtime()
|
|
{
|
|
realtimeService.MessageReceived -= OnRealtimeChanged;
|
|
realtimeService.MessageUpdated -= OnRealtimeChanged;
|
|
realtimeService.ChatCreated -= OnChatCreated;
|
|
realtimeService.ChatsChanged -= OnRealtimeChanged;
|
|
|
|
realtimeService.MessageReceived += OnRealtimeChanged;
|
|
realtimeService.MessageUpdated += OnRealtimeChanged;
|
|
realtimeService.ChatCreated += OnChatCreated;
|
|
realtimeService.ChatsChanged += OnRealtimeChanged;
|
|
}
|
|
|
|
private void OnChatCreated(object? sender, ChatSummaryDto e)
|
|
{
|
|
MainThread.BeginInvokeOnMainThread(() => _ = LoadAsync());
|
|
}
|
|
|
|
private void OnRealtimeChanged(object? sender, EventArgs e)
|
|
{
|
|
MainThread.BeginInvokeOnMainThread(() => _ = LoadAsync());
|
|
}
|
|
|
|
private void OnRealtimeChanged(object? sender, MessageDto e)
|
|
{
|
|
MainThread.BeginInvokeOnMainThread(() => _ = LoadAsync());
|
|
}
|
|
}
|