// 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 class TrackCollectionViewModel : ObservableObject, ISdkViewModel, ITrackCollectionViewModel, IImageCollectionViewModel
{
private readonly ITrackCollection _collection;
private readonly SemaphoreSlim _populateTracksMutex = new(1, 1);
private readonly SemaphoreSlim _populateImagesMutex = new(1, 1);
private readonly SemaphoreSlim _populateUrlsMutex = new(1, 1);
private readonly SynchronizationContext _syncContext;
///
/// Initializes a new instance of the class.
///
/// The base containing properties about this class.
public TrackCollectionViewModel(ITrackCollection collection)
{
_syncContext = SynchronizationContext.Current;
_collection = collection;
Tracks = new ObservableCollection();
Images = new ObservableCollection();
Urls = new ObservableCollection();
UnsortedTracks = new ObservableCollection();
PopulateMoreTracksCommand = new AsyncRelayCommand(PopulateMoreTracksAsync);
PopulateMoreImagesCommand = new AsyncRelayCommand(PopulateMoreImagesAsync);
PopulateMoreUrlsCommand = new AsyncRelayCommand(PopulateMoreUrlsAsync);
PauseTrackCollectionAsyncCommand = new AsyncRelayCommand(PauseTrackCollectionAsync);
PlayTrackCollectionAsyncCommand = new AsyncRelayCommand(PlayTrackCollectionAsync);
PlayTrackAsyncCommand = new AsyncRelayCommand((x, y) => _collection.PlayTrackCollectionAsync(x ?? ThrowHelper.ThrowArgumentNullException(nameof(x)), y));
ChangeNameAsyncCommand = new AsyncRelayCommand(ChangeNameInternalAsync);
ChangeDescriptionAsyncCommand = new AsyncRelayCommand(ChangeDescriptionAsync);
ChangeDurationAsyncCommand = new AsyncRelayCommand(ChangeDurationAsync);
ChangeTrackCollectionSortingTypeCommand = new RelayCommand(x => SortTrackCollection(x, CurrentTracksSortingDirection));
ChangeTrackCollectionSortingDirectionCommand = new RelayCommand(x => SortTrackCollection(CurrentTracksSortingType, x));
InitImageCollectionAsyncCommand = new AsyncRelayCommand(InitImageCollectionAsync);
InitTrackCollectionAsyncCommand = new AsyncRelayCommand(InitTrackCollectionAsync);
AttachEvents();
}
///
public Task InitAsync(CancellationToken cancellationToken = default)
{
if (IsInitialized)
return Task.CompletedTask;
IsInitialized = true;
return Task.WhenAll(InitImageCollectionAsync(cancellationToken), InitTrackCollectionAsync(cancellationToken));
}
private void AttachEvents()
{
PlaybackStateChanged += OnPlaybackStateChanged;
NameChanged += OnNameChanged;
DescriptionChanged += OnDescriptionChanged;
LastPlayedChanged += OnLastPlayedChanged;
DownloadInfoChanged += OnDownloadInfoChanged;
IsPlayTrackCollectionAsyncAvailableChanged += OnIsPlayTrackCollectionAsyncAvailableChanged;
IsPauseTrackCollectionAsyncAvailableChanged += OnIsPauseTrackCollectionAsyncAvailableChanged;
IsChangeNameAsyncAvailableChanged += OnIsChangeNameAsyncAvailableChanged;
IsChangeDurationAsyncAvailableChanged += OnIsChangeDurationAsyncAvailableChanged;
IsChangeDescriptionAsyncAvailableChanged += OnIsChangeDescriptionAsyncAvailableChanged;
TracksCountChanged += OnTrackItemsCountChanged;
TracksChanged += TrackCollectionViewModel_TrackItemsChanged;
ImagesChanged += TrackCollectionViewModel_ImagesChanged;
ImagesCountChanged += TrackCollectionViewModel_ImagesCountChanged;
UrlsChanged += TrackCollectionViewModel_UrlsChanged;
UrlsCountChanged += TrackCollectionViewModel_UrlsCountChanged;
}
private void DetachEvents()
{
PlaybackStateChanged -= OnPlaybackStateChanged;
NameChanged -= OnNameChanged;
DescriptionChanged -= OnDescriptionChanged;
LastPlayedChanged -= OnLastPlayedChanged;
DownloadInfoChanged -= OnDownloadInfoChanged;
IsPlayTrackCollectionAsyncAvailableChanged -= OnIsPlayTrackCollectionAsyncAvailableChanged;
IsPauseTrackCollectionAsyncAvailableChanged -= OnIsPauseTrackCollectionAsyncAvailableChanged;
IsChangeNameAsyncAvailableChanged -= OnIsChangeNameAsyncAvailableChanged;
IsChangeDurationAsyncAvailableChanged -= OnIsChangeDurationAsyncAvailableChanged;
IsChangeDescriptionAsyncAvailableChanged -= OnIsChangeDescriptionAsyncAvailableChanged;
TracksCountChanged -= OnTrackItemsCountChanged;
TracksChanged -= TrackCollectionViewModel_TrackItemsChanged;
ImagesChanged -= TrackCollectionViewModel_ImagesChanged;
ImagesCountChanged -= TrackCollectionViewModel_ImagesCountChanged;
UrlsChanged -= TrackCollectionViewModel_UrlsChanged;
UrlsCountChanged -= TrackCollectionViewModel_UrlsCountChanged;
}
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 OnLastPlayedChanged(object sender, DateTime? e) => _syncContext.Post(_ => OnPropertyChanged(nameof(LastPlayed)), null);
private void OnTrackItemsCountChanged(object sender, int e) => _syncContext.Post(_ => OnPropertyChanged(nameof(TotalTrackCount)), null);
private void TrackCollectionViewModel_ImagesCountChanged(object sender, int e) => _syncContext.Post(_ => OnPropertyChanged(nameof(TotalImageCount)), null);
private void TrackCollectionViewModel_UrlsCountChanged(object sender, int e) => _syncContext.Post(_ => OnPropertyChanged(nameof(TotalUrlCount)), 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 OnIsPauseTrackCollectionAsyncAvailableChanged(object sender, bool e) => _syncContext.Post(_ => OnPropertyChanged(nameof(IsPauseTrackCollectionAsyncAvailable)), null);
private void OnIsPlayTrackCollectionAsyncAvailableChanged(object sender, bool e) => _syncContext.Post(_ => OnPropertyChanged(nameof(IsPlayTrackCollectionAsyncAvailable)), null);
private void TrackCollectionViewModel_TrackItemsChanged(object sender, IReadOnlyList> addedItems, IReadOnlyList> removedItems) => _syncContext.Post(_ =>
{
if (CurrentTracksSortingType == TrackSortingType.Unsorted)
{
Tracks.ChangeCollection(addedItems, removedItems, x => new TrackViewModel(x.Data));
}
else
{
// Make sure both ordered and unordered tracks are updated.
UnsortedTracks.ChangeCollection(addedItems, removedItems, x => new TrackViewModel(x.Data));
foreach (var item in UnsortedTracks)
{
if (!Tracks.Contains(item))
Tracks.Add(item);
}
foreach (var item in Tracks.ToArray())
{
if (!UnsortedTracks.Contains(item))
Tracks.Remove(item);
}
SortTrackCollection(CurrentTracksSortingType, CurrentTracksSortingDirection);
}
}, null);
private void TrackCollectionViewModel_ImagesChanged(object sender, IReadOnlyList> addedItems, IReadOnlyList> removedItems) => _syncContext.Post(_ =>
{
Images.ChangeCollection(addedItems, removedItems);
}, null);
private void TrackCollectionViewModel_UrlsChanged(object sender, IReadOnlyList> addedItems, IReadOnlyList> removedItems) => _syncContext.Post(_ =>
{
Urls.ChangeCollection(addedItems, removedItems);
}, null);
///
public event EventHandler? SourcesChanged
{
add => _collection.SourcesChanged += value;
remove => _collection.SourcesChanged -= value;
}
///
public event EventHandler? IsPlayTrackCollectionAsyncAvailableChanged
{
add => _collection.IsPlayTrackCollectionAsyncAvailableChanged += value;
remove => _collection.IsPlayTrackCollectionAsyncAvailableChanged -= value;
}
///
public event EventHandler? IsPauseTrackCollectionAsyncAvailableChanged
{
add => _collection.IsPauseTrackCollectionAsyncAvailableChanged += value;
remove => _collection.IsPauseTrackCollectionAsyncAvailableChanged -= 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? TracksCountChanged
{
add => _collection.TracksCountChanged += value;
remove => _collection.TracksCountChanged -= value;
}
///
public event CollectionChangedEventHandler? TracksChanged
{
add => _collection.TracksChanged += value;
remove => _collection.TracksChanged -= value;
}
///
public event EventHandler? ImagesCountChanged
{
add => _collection.ImagesCountChanged += value;
remove => _collection.ImagesCountChanged -= value;
}
///
public event CollectionChangedEventHandler? ImagesChanged
{
add => _collection.ImagesChanged += value;
remove => _collection.ImagesChanged -= value;
}
///
public event EventHandler? UrlsCountChanged
{
add => _collection.UrlsCountChanged += value;
remove => _collection.UrlsCountChanged -= value;
}
///
public event CollectionChangedEventHandler? UrlsChanged
{
add => _collection.UrlsChanged += value;
remove => _collection.UrlsChanged -= value;
}
///
public bool IsInitialized { get; private set; }
///
public string Id => _collection.Id;
///
public bool IsPlayTrackCollectionAsyncAvailable => _collection.IsPlayTrackCollectionAsyncAvailable;
///
public bool IsPauseTrackCollectionAsyncAvailable => _collection.IsPauseTrackCollectionAsyncAvailable;
///
public bool IsChangeNameAsyncAvailable => _collection.IsChangeNameAsyncAvailable;
///
public bool IsChangeDescriptionAsyncAvailable => _collection.IsChangeDescriptionAsyncAvailable;
///
public bool IsChangeDurationAsyncAvailable => _collection.IsChangeDurationAsyncAvailable;
///
public string Name => _collection.Name;
///
public int TotalTrackCount => _collection.TotalTrackCount;
///
public int TotalImageCount => _collection.TotalImageCount;
///
public int TotalUrlCount => _collection.TotalUrlCount;
///
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 TrackSortingType CurrentTracksSortingType { get; private set; }
///
public SortDirection CurrentTracksSortingDirection { get; private set; }
///
public ObservableCollection UnsortedTracks { get; }
///
public ObservableCollection Tracks { get; }
///
public ObservableCollection Images { get; }
///
public ObservableCollection Urls { get; }
///
/// The sources that were merged into this collection.
///
public IReadOnlyList Sources => _collection.GetSources();
///
IReadOnlyList IMerged.Sources => Sources;
///
IReadOnlyList IMerged.Sources => Sources;
///
IReadOnlyList IMerged.Sources => Sources;
///
public Task IsAddTrackAvailableAsync(int index, CancellationToken cancellationToken = default) => _collection.IsAddTrackAvailableAsync(index, cancellationToken);
///
public Task IsRemoveTrackAvailableAsync(int index, CancellationToken cancellationToken = default) => _collection.IsRemoveTrackAvailableAsync(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 StartDownloadOperationAsync(DownloadOperation operation, CancellationToken cancellationToken = default) => _collection.StartDownloadOperationAsync(operation, cancellationToken);
///
public Task ChangeNameAsync(string name, CancellationToken cancellationToken = default) => ChangeNameInternalAsync(name, cancellationToken);
///
public Task AddTrackAsync(ITrack track, int index, CancellationToken cancellationToken = default) => _collection.AddTrackAsync(track, index, cancellationToken);
///
public Task RemoveTrackAsync(int index, CancellationToken cancellationToken = default) => _collection.RemoveTrackAsync(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 IAsyncEnumerable GetTracksAsync(int limit, int offset, CancellationToken cancellationToken = default) => _collection.GetTracksAsync(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);
///
public Task PlayTrackCollectionAsync(CancellationToken cancellationToken = default) => _collection.PlayTrackCollectionAsync(cancellationToken);
///
public Task PlayTrackCollectionAsync(ITrack track, CancellationToken cancellationToken = default) => _collection.PlayTrackCollectionAsync(track, cancellationToken);
///
public Task PauseTrackCollectionAsync(CancellationToken cancellationToken = default) => _collection.PauseTrackCollectionAsync(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 void SortTrackCollection(TrackSortingType trackSorting, SortDirection sortDirection)
{
CurrentTracksSortingType = trackSorting;
CurrentTracksSortingDirection = sortDirection;
CollectionSorting.SortTracks(Tracks, trackSorting, sortDirection, UnsortedTracks);
}
///
public async Task PopulateMoreTracksAsync(int limit, CancellationToken cancellationToken = default)
{
using (await Flow.EasySemaphore(_populateTracksMutex))
{
using var releaseReg = cancellationToken.Register(() => _populateTracksMutex.Release());
_syncContext.Post(async _ =>
{
await foreach (var item in _collection.GetTracksAsync(limit, Tracks.Count, cancellationToken))
{
var tvm = new TrackViewModel(item);
Tracks.Add(tvm);
UnsortedTracks.Add(tvm);
}
}, 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 Task InitImageCollectionAsync(CancellationToken cancellationToken = default) => CollectionInit.ImageCollection(this, cancellationToken);
///
public Task InitTrackCollectionAsync(CancellationToken cancellationToken = default) => CollectionInit.TrackCollection(this, cancellationToken);
///
public IRelayCommand ChangeTrackCollectionSortingTypeCommand { get; }
///
public IRelayCommand ChangeTrackCollectionSortingDirectionCommand { get; }
///
public IAsyncRelayCommand PopulateMoreTracksCommand { get; }
///
public IAsyncRelayCommand PopulateMoreImagesCommand { get; }
///
public IAsyncRelayCommand PopulateMoreUrlsCommand { get; }
///
public IAsyncRelayCommand PlayTrackCollectionAsyncCommand { get; }
///
public IAsyncRelayCommand PlayTrackAsyncCommand { get; }
///
public IAsyncRelayCommand PauseTrackCollectionAsyncCommand { 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 InitTrackCollectionAsyncCommand { get; }
///
public IAsyncRelayCommand InitImageCollectionAsyncCommand { get; }
///
public bool Equals(ICoreTrackCollection 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 ValueTask DisposeAsync()
{
DetachEvents();
return _collection.DisposeAsync();
}
}
}