// Copyright (c) Arlo Godfrey. All Rights Reserved. // Licensed under the GNU Lesser General Public License, Version 3.0 with additional terms. // See the LICENSE, LICENSE.LESSER and LICENSE.ADDITIONAL files in the project root for more information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using CommunityToolkit.Diagnostics; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using OwlCore; using OwlCore.Events; using OwlCore.Extensions; using StrixMusic.Sdk.AdapterModels; using StrixMusic.Sdk.AppModels; using StrixMusic.Sdk.CoreModels; using StrixMusic.Sdk.Extensions; using StrixMusic.Sdk.MediaPlayback; using StrixMusic.Sdk.ViewModels.Helpers; namespace StrixMusic.Sdk.ViewModels { /// /// A ViewModel for . /// public sealed class AlbumCollectionViewModel : ObservableObject, ISdkViewModel, IAlbumCollectionViewModel, IUrlCollectionViewModel, IImageCollectionViewModel { private readonly IAlbumCollection _collection; private readonly SemaphoreSlim _populateAlbumsMutex = new(1, 1); private readonly SemaphoreSlim _populateImagesMutex = new(1, 1); private readonly SemaphoreSlim _populateUrlsMutex = new(1, 1); private readonly SynchronizationContext _syncContext; /// /// Creates a new instance of . /// /// The to wrap around. public AlbumCollectionViewModel(IAlbumCollection collection) { _syncContext = SynchronizationContext.Current; _collection = collection; Albums = new ObservableCollection(); UnsortedAlbums = new ObservableCollection(); Images = new ObservableCollection(); Urls = new ObservableCollection(); PopulateMoreAlbumsCommand = new AsyncRelayCommand(PopulateMoreAlbumsAsync); PopulateMoreImagesCommand = new AsyncRelayCommand(PopulateMoreImagesAsync); PopulateMoreUrlsCommand = new AsyncRelayCommand(PopulateMoreUrlsAsync); PauseAlbumCollectionAsyncCommand = new AsyncRelayCommand(PauseAlbumCollectionAsync); PlayAlbumCollectionAsyncCommand = new AsyncRelayCommand(PlayAlbumCollectionAsync); ChangeNameAsyncCommand = new AsyncRelayCommand(ChangeNameInternalAsync); ChangeDescriptionAsyncCommand = new AsyncRelayCommand(ChangeDescriptionAsync); ChangeDurationAsyncCommand = new AsyncRelayCommand(ChangeDurationAsync); ChangeAlbumCollectionSortingTypeCommand = new RelayCommand(x => SortAlbumCollection(x, CurrentAlbumSortingDirection)); ChangeAlbumCollectionSortingDirectionCommand = new RelayCommand(x => SortAlbumCollection(CurrentAlbumSortingType, x)); InitAlbumCollectionAsyncCommand = new AsyncRelayCommand(InitAlbumCollectionAsync); InitImageCollectionAsyncCommand = new AsyncRelayCommand(InitImageCollectionAsync); PlayAlbumAsyncCommand = new AsyncRelayCommand((x, y) => _collection.PlayAlbumCollectionAsync(x ?? ThrowHelper.ThrowArgumentNullException(nameof(x)), y)); AttachEvents(); } private void AttachEvents() { PlaybackStateChanged += OnPlaybackStateChanged; NameChanged += OnNameChanged; DescriptionChanged += OnDescriptionChanged; LastPlayedChanged += OnLastPlayedChanged; DownloadInfoChanged += OnDownloadInfoChanged; IsPlayAlbumCollectionAsyncAvailableChanged += OnIsPlayAlbumCollectionAsyncAvailableChanged; IsPauseAlbumCollectionAsyncAvailableChanged += OnIsPauseAlbumCollectionAsyncAvailableChanged; IsChangeNameAsyncAvailableChanged += OnIsChangeNameAsyncAvailableChanged; IsChangeDurationAsyncAvailableChanged += OnIsChangeDurationAsyncAvailableChanged; IsChangeDescriptionAsyncAvailableChanged += OnIsChangeDescriptionAsyncAvailableChanged; AlbumItemsCountChanged += OnAlbumItemsCountChanged; AlbumItemsChanged += AlbumCollectionViewModel_AlbumItemsChanged; ImagesCountChanged += OnImagesCountChanged; ImagesChanged += AlbumCollectionViewModel_ImagesChanged; UrlsCountChanged += OnUrlsCountChanged; UrlsChanged += AlbumCollectionViewModel_UrlsChanged; } private void DetachEvents() { PlaybackStateChanged -= OnPlaybackStateChanged; NameChanged -= OnNameChanged; DescriptionChanged -= OnDescriptionChanged; LastPlayedChanged -= OnLastPlayedChanged; DownloadInfoChanged -= OnDownloadInfoChanged; IsPlayAlbumCollectionAsyncAvailableChanged -= OnIsPlayAlbumCollectionAsyncAvailableChanged; IsPauseAlbumCollectionAsyncAvailableChanged -= OnIsPauseAlbumCollectionAsyncAvailableChanged; IsChangeNameAsyncAvailableChanged -= OnIsChangeNameAsyncAvailableChanged; IsChangeDurationAsyncAvailableChanged -= OnIsChangeDurationAsyncAvailableChanged; IsChangeDescriptionAsyncAvailableChanged -= OnIsChangeDescriptionAsyncAvailableChanged; AlbumItemsCountChanged -= OnAlbumItemsCountChanged; AlbumItemsChanged -= AlbumCollectionViewModel_AlbumItemsChanged; ImagesCountChanged -= OnImagesCountChanged; ImagesChanged -= AlbumCollectionViewModel_ImagesChanged; } private void OnNameChanged(object sender, string e) => _syncContext.Post(_ => OnPropertyChanged(nameof(Name)), null); private void OnDescriptionChanged(object sender, string? e) => _syncContext.Post(_ => OnPropertyChanged(nameof(Description)), null); private void OnPlaybackStateChanged(object sender, PlaybackState e) => _syncContext.Post(_ => OnPropertyChanged(nameof(PlaybackState)), null); private void OnDownloadInfoChanged(object sender, DownloadInfo e) => _syncContext.Post(_ => OnPropertyChanged(nameof(DownloadInfo)), null); private void OnAlbumItemsCountChanged(object sender, int e) => _syncContext.Post(_ => OnPropertyChanged(nameof(TotalAlbumItemsCount)), null); private void OnImagesCountChanged(object sender, int e) => _syncContext.Post(_ => OnPropertyChanged(nameof(TotalImageCount)), null); private void OnUrlsCountChanged(object sender, int e) => _syncContext.Post(_ => OnPropertyChanged(nameof(TotalUrlCount)), null); private void OnLastPlayedChanged(object sender, DateTime? e) => _syncContext.Post(_ => OnPropertyChanged(nameof(LastPlayed)), null); private void OnIsChangeDescriptionAsyncAvailableChanged(object sender, bool e) => _syncContext.Post(_ => OnPropertyChanged(nameof(IsChangeDescriptionAsyncAvailable)), null); private void OnIsChangeDurationAsyncAvailableChanged(object sender, bool e) => _syncContext.Post(_ => OnPropertyChanged(nameof(IsChangeDurationAsyncAvailable)), null); private void OnIsChangeNameAsyncAvailableChanged(object sender, bool e) => _syncContext.Post(_ => OnPropertyChanged(nameof(IsChangeNameAsyncAvailable)), null); private void OnIsPauseAlbumCollectionAsyncAvailableChanged(object sender, bool e) => _syncContext.Post(_ => OnPropertyChanged(nameof(IsPauseAlbumCollectionAsyncAvailable)), null); private void OnIsPlayAlbumCollectionAsyncAvailableChanged(object sender, bool e) => _syncContext.Post(_ => OnPropertyChanged(nameof(IsPlayAlbumCollectionAsyncAvailable)), null); private void AlbumCollectionViewModel_ImagesChanged(object sender, IReadOnlyList> addedItems, IReadOnlyList> removedItems) => _syncContext.Post(_ => { Images.ChangeCollection(addedItems, removedItems); }, null); private void AlbumCollectionViewModel_UrlsChanged(object sender, IReadOnlyList> addedItems, IReadOnlyList> removedItems) => _syncContext.Post(_ => { Urls.ChangeCollection(addedItems, removedItems); }, null); private void AlbumCollectionViewModel_AlbumItemsChanged(object sender, IReadOnlyList> addedItems, IReadOnlyList> removedItems) => _syncContext.Post(_ => { if (CurrentAlbumSortingType == AlbumSortingType.Unsorted) { Albums.ChangeCollection(addedItems, removedItems, item => item.Data switch { IAlbum album => new AlbumViewModel(album), IAlbumCollection collection => new AlbumCollectionViewModel(collection), _ => ThrowHelper.ThrowNotSupportedException( $"{item.Data.GetType()} not supported for adding to {GetType()}") }); } else { // Preventing index issues during albums emission from the core, also making sure that unordered albums updated. UnsortedAlbums.ChangeCollection(addedItems, removedItems, item => item.Data switch { IAlbum album => new AlbumViewModel(album), IAlbumCollection collection => new AlbumCollectionViewModel(collection), _ => ThrowHelper.ThrowNotSupportedException( $"{item.Data.GetType()} not supported for adding to {GetType()}") }); foreach (var item in UnsortedAlbums) { if (!Albums.Contains(item)) Albums.Add(item); } foreach (var item in Albums.ToArray()) { if (!UnsortedAlbums.Contains(item)) Albums.Remove(item); } SortAlbumCollection(CurrentAlbumSortingType, CurrentAlbumSortingDirection); } }, null); /// public event EventHandler? SourcesChanged { add => _collection.SourcesChanged += value; remove => _collection.SourcesChanged -= value; } /// public event EventHandler? PlaybackStateChanged { add => _collection.PlaybackStateChanged += value; remove => _collection.PlaybackStateChanged -= value; } /// public event EventHandler? DownloadInfoChanged { add => _collection.DownloadInfoChanged += value; remove => _collection.DownloadInfoChanged -= value; } /// public event EventHandler? NameChanged { add => _collection.NameChanged += value; remove => _collection.NameChanged -= value; } /// public event EventHandler? DescriptionChanged { add => _collection.DescriptionChanged += value; remove => _collection.DescriptionChanged -= value; } /// public event EventHandler? DurationChanged { add => _collection.DurationChanged += value; remove => _collection.DurationChanged -= value; } /// public event EventHandler? LastPlayedChanged { add => _collection.LastPlayedChanged += value; remove => _collection.LastPlayedChanged -= value; } /// public event EventHandler? IsChangeNameAsyncAvailableChanged { add => _collection.IsChangeNameAsyncAvailableChanged += value; remove => _collection.IsChangeNameAsyncAvailableChanged -= value; } /// public event EventHandler? IsChangeDescriptionAsyncAvailableChanged { add => _collection.IsChangeDescriptionAsyncAvailableChanged += value; remove => _collection.IsChangeDescriptionAsyncAvailableChanged -= value; } /// public event EventHandler? IsChangeDurationAsyncAvailableChanged { add => _collection.IsChangeDurationAsyncAvailableChanged += value; remove => _collection.IsChangeDurationAsyncAvailableChanged -= value; } /// public event EventHandler? IsPlayAlbumCollectionAsyncAvailableChanged { add => _collection.IsPlayAlbumCollectionAsyncAvailableChanged += value; remove => _collection.IsPlayAlbumCollectionAsyncAvailableChanged -= value; } /// public event EventHandler? IsPauseAlbumCollectionAsyncAvailableChanged { add => _collection.IsPauseAlbumCollectionAsyncAvailableChanged += value; remove => _collection.IsPauseAlbumCollectionAsyncAvailableChanged -= value; } /// public event EventHandler? AlbumItemsCountChanged { add => _collection.AlbumItemsCountChanged += value; remove => _collection.AlbumItemsCountChanged -= value; } /// public event CollectionChangedEventHandler? ImagesChanged { add => _collection.ImagesChanged += value; remove => _collection.ImagesChanged -= value; } /// public event EventHandler? ImagesCountChanged { add => _collection.ImagesCountChanged += value; remove => _collection.ImagesCountChanged -= value; } /// public event CollectionChangedEventHandler? UrlsChanged { add => _collection.UrlsChanged += value; remove => _collection.UrlsChanged -= value; } /// public event EventHandler? UrlsCountChanged { add => _collection.UrlsCountChanged += value; remove => _collection.UrlsCountChanged -= value; } /// public event CollectionChangedEventHandler? AlbumItemsChanged { add => _collection.AlbumItemsChanged += value; remove => _collection.AlbumItemsChanged -= value; } /// public async Task PopulateMoreAlbumsAsync(int limit, CancellationToken cancellationToken = default) { using (await Flow.EasySemaphore(_populateAlbumsMutex)) { using var releaseReg = cancellationToken.Register(() => _populateAlbumsMutex.Release()); _syncContext.Post(async _ => { await foreach (var item in _collection.GetAlbumItemsAsync(limit, Albums.Count, cancellationToken)) { switch (item) { case IAlbum album: var avm = new AlbumViewModel(album); Albums.Add(avm); UnsortedAlbums.Add(avm); break; case IAlbumCollection collection: var acvm = new AlbumCollectionViewModel(collection); Albums.Add(acvm); UnsortedAlbums.Add(acvm); break; } } }, null); } } /// public async Task PopulateMoreImagesAsync(int limit, CancellationToken cancellationToken = default) { using (await Flow.EasySemaphore(_populateImagesMutex)) { using var releaseReg = cancellationToken.Register(() => _populateImagesMutex.Release()); _syncContext.Post(async _ => { await foreach (var item in _collection.GetImagesAsync(limit, Images.Count, cancellationToken)) Images.Add(item); }, null); } } /// public async Task PopulateMoreUrlsAsync(int limit, CancellationToken cancellationToken = default) { using (await Flow.EasySemaphore(_populateUrlsMutex)) { using var releaseReg = cancellationToken.Register(() => _populateUrlsMutex.Release()); _syncContext.Post(async _ => { await foreach (var item in _collection.GetUrlsAsync(limit, Urls.Count, cancellationToken)) Urls.Add(item); }, null); } } /// public void SortAlbumCollection(AlbumSortingType albumSorting, SortDirection sortDirection) { CurrentAlbumSortingType = albumSorting; CurrentAlbumSortingDirection = sortDirection; CollectionSorting.SortAlbums(Albums, albumSorting, sortDirection, UnsortedAlbums); } /// public ObservableCollection Albums { get; } /// public ObservableCollection UnsortedAlbums { get; } /// public ObservableCollection Images { get; } /// public ObservableCollection Urls { get; } /// public AlbumSortingType CurrentAlbumSortingType { get; private set; } /// public SortDirection CurrentAlbumSortingDirection { get; private set; } /// public string Id => _collection.Id; /// public string Name => _collection.Name; /// public string? Description => _collection.Description; /// public PlaybackState PlaybackState => _collection.PlaybackState; /// public DownloadInfo DownloadInfo => _collection.DownloadInfo; /// public TimeSpan Duration => _collection.Duration; /// public DateTime? LastPlayed => _collection.LastPlayed; /// public DateTime? AddedAt => _collection.AddedAt; /// public int TotalAlbumItemsCount => _collection.TotalAlbumItemsCount; /// public bool IsPlayAlbumCollectionAsyncAvailable => _collection.IsPlayAlbumCollectionAsyncAvailable; /// public bool IsPauseAlbumCollectionAsyncAvailable => _collection.IsPauseAlbumCollectionAsyncAvailable; /// public int TotalImageCount => _collection.TotalImageCount; /// public int TotalUrlCount => _collection.TotalUrlCount; /// public bool IsChangeNameAsyncAvailable => _collection.IsChangeNameAsyncAvailable; /// public bool IsChangeDescriptionAsyncAvailable => _collection.IsChangeDescriptionAsyncAvailable; /// public bool IsChangeDurationAsyncAvailable => _collection.IsChangeDurationAsyncAvailable; /// public Task IsAddAlbumItemAvailableAsync(int index, CancellationToken cancellationToken = default) => _collection.IsAddAlbumItemAvailableAsync(index, cancellationToken); /// public Task IsRemoveAlbumItemAvailableAsync(int index, CancellationToken cancellationToken = default) => _collection.IsRemoveAlbumItemAvailableAsync(index, cancellationToken); /// public Task IsAddImageAvailableAsync(int index, CancellationToken cancellationToken = default) => _collection.IsAddImageAvailableAsync(index, cancellationToken); /// public Task IsRemoveImageAvailableAsync(int index, CancellationToken cancellationToken = default) => _collection.IsRemoveImageAvailableAsync(index, cancellationToken); /// public Task IsAddUrlAvailableAsync(int index, CancellationToken cancellationToken = default) => _collection.IsAddUrlAvailableAsync(index, cancellationToken); /// public Task IsRemoveUrlAvailableAsync(int index, CancellationToken cancellationToken = default) => _collection.IsRemoveUrlAvailableAsync(index, cancellationToken); /// public Task ChangeNameAsync(string name, CancellationToken cancellationToken = default) => ChangeNameInternalAsync(name, cancellationToken); /// public Task ChangeDescriptionAsync(string? description, CancellationToken cancellationToken = default) => _collection.ChangeDescriptionAsync(description, cancellationToken); /// public Task ChangeDurationAsync(TimeSpan duration, CancellationToken cancellationToken = default) => _collection.ChangeDurationAsync(duration, cancellationToken); /// public Task StartDownloadOperationAsync(DownloadOperation operation, CancellationToken cancellationToken = default) => _collection.StartDownloadOperationAsync(operation, cancellationToken); /// public IAsyncEnumerable GetAlbumItemsAsync(int limit, int offset, CancellationToken cancellationToken = default) => _collection.GetAlbumItemsAsync(limit, offset, cancellationToken); /// public IAsyncEnumerable GetImagesAsync(int limit, int offset, CancellationToken cancellationToken = default) => _collection.GetImagesAsync(limit, offset, cancellationToken); /// public IAsyncEnumerable GetUrlsAsync(int limit, int offset, CancellationToken cancellationToken = default) => _collection.GetUrlsAsync(limit, offset, cancellationToken); /// /// The sources for this item. /// public IReadOnlyList Sources => _collection.GetSources(); /// IReadOnlyList IMerged.Sources => _collection.GetSources(); /// IReadOnlyList IMerged.Sources => _collection.GetSources(); /// IReadOnlyList IMerged.Sources => _collection.GetSources(); /// IReadOnlyList IMerged.Sources => _collection.GetSources(); /// public Task PlayAlbumCollectionAsync(CancellationToken cancellationToken = default) => _collection.PlayAlbumCollectionAsync(cancellationToken); /// public Task PlayAlbumCollectionAsync(IAlbumCollectionItem albumItem, CancellationToken cancellationToken = default) => _collection.PlayAlbumCollectionAsync(albumItem, cancellationToken); /// public Task PauseAlbumCollectionAsync(CancellationToken cancellationToken = default) => _collection.PauseAlbumCollectionAsync(cancellationToken); /// public Task AddAlbumItemAsync(IAlbumCollectionItem album, int index, CancellationToken cancellationToken = default) => _collection.AddAlbumItemAsync(album, index, cancellationToken); /// public Task RemoveAlbumItemAsync(int index, CancellationToken cancellationToken = default) => _collection.RemoveAlbumItemAsync(index, cancellationToken); /// public Task AddImageAsync(IImage image, int index, CancellationToken cancellationToken = default) => _collection.AddImageAsync(image, index, cancellationToken); /// public Task RemoveImageAsync(int index, CancellationToken cancellationToken = default) => _collection.RemoveImageAsync(index, cancellationToken); /// public Task AddUrlAsync(IUrl image, int index, CancellationToken cancellationToken = default) => _collection.AddUrlAsync(image, index, cancellationToken); /// public Task RemoveUrlAsync(int index, CancellationToken cancellationToken = default) => _collection.RemoveUrlAsync(index, cancellationToken); /// public Task InitAlbumCollectionAsync(CancellationToken cancellationToken = default) => CollectionInit.AlbumCollection(this, cancellationToken); /// public Task InitImageCollectionAsync(CancellationToken cancellationToken = default) => CollectionInit.ImageCollection(this, cancellationToken); /// public IAsyncRelayCommand InitAlbumCollectionAsyncCommand { get; } /// public IAsyncRelayCommand PopulateMoreAlbumsCommand { get; } /// public IAsyncRelayCommand PopulateMoreImagesCommand { get; } /// public IAsyncRelayCommand PopulateMoreUrlsCommand { get; } /// public IAsyncRelayCommand PlayAlbumCollectionAsyncCommand { get; } /// public IAsyncRelayCommand PlayAlbumAsyncCommand { get; } /// public IAsyncRelayCommand PauseAlbumCollectionAsyncCommand { get; } /// public IRelayCommand ChangeAlbumCollectionSortingTypeCommand { get; } /// public IRelayCommand ChangeAlbumCollectionSortingDirectionCommand { get; } /// /// Command to change the name. It triggers . /// public IAsyncRelayCommand ChangeNameAsyncCommand { get; } /// /// Command to change the description. It triggers . /// public IAsyncRelayCommand ChangeDescriptionAsyncCommand { get; } /// /// Command to change the duration. It triggers . /// public IAsyncRelayCommand ChangeDurationAsyncCommand { get; } /// public IAsyncRelayCommand InitImageCollectionAsyncCommand { get; } /// public bool Equals(ICoreAlbumCollectionItem other) => _collection.Equals(other); /// public bool Equals(ICoreAlbumCollection other) => _collection.Equals(other); /// public bool Equals(ICoreImageCollection other) => _collection.Equals(other); /// public bool Equals(ICoreUrlCollection other) => _collection.Equals(other); private Task ChangeNameInternalAsync(string? name, CancellationToken cancellationToken = default) { Guard.IsNotNull(name, nameof(name)); return _collection.ChangeNameAsync(name, cancellationToken); } /// public bool IsInitialized { get; private set; } /// public Task InitAsync(CancellationToken cancellationToken = default) { if (IsInitialized) return Task.CompletedTask; IsInitialized = true; return Task.WhenAll(InitAlbumCollectionAsync(cancellationToken), InitImageCollectionAsync(cancellationToken)); } /// public ValueTask DisposeAsync() { DetachEvents(); return _collection.DisposeAsync(); } } }