84 lines
2.2 KiB
C#
84 lines
2.2 KiB
C#
namespace Harmonia.Core.Playlists;
|
|
|
|
public class PlaylistManager : IPlaylistManager
|
|
{
|
|
private readonly IPlaylistRepository playlistRepository;
|
|
private readonly List<Playlist> _playlists = [];
|
|
|
|
public IReadOnlyList<Playlist> Playlists => _playlists;
|
|
|
|
private Playlist? _currentPlaylist;
|
|
public Playlist? CurrentPlaylist
|
|
{
|
|
get
|
|
{
|
|
return _currentPlaylist;
|
|
}
|
|
set
|
|
{
|
|
_currentPlaylist = value;
|
|
CurrentPlaylistChanged?.Invoke(this, new());
|
|
}
|
|
}
|
|
|
|
public event EventHandler? CurrentPlaylistChanged;
|
|
public event EventHandler<PlaylistAddedEventArgs>? PlaylistAdded;
|
|
public event EventHandler<PlaylistRemovedEventArgs>? PlaylistRemoved;
|
|
|
|
public PlaylistManager(IPlaylistRepository playlistRepository)
|
|
{
|
|
this.playlistRepository = playlistRepository;
|
|
}
|
|
|
|
public async Task InitializeAsync()
|
|
{
|
|
_playlists.AddRange(playlistRepository.Get());
|
|
|
|
foreach (Playlist playlist in _playlists)
|
|
{
|
|
playlist.PlaylistUpdated += OnPlaylistUpdated;
|
|
}
|
|
|
|
CurrentPlaylist = _playlists.Count > 0 ? _playlists[0] : await AddPlaylistAsync();
|
|
}
|
|
|
|
public async Task<Playlist> AddPlaylistAsync()
|
|
{
|
|
Playlist playlist = new()
|
|
{
|
|
Name = "New Playlist"
|
|
};
|
|
|
|
playlist.PlaylistUpdated += OnPlaylistUpdated;
|
|
_playlists.Add(playlist);
|
|
|
|
await playlistRepository.SaveAsync(playlist);
|
|
|
|
PlaylistAdded?.Invoke(this, new(playlist));
|
|
|
|
return playlist;
|
|
}
|
|
|
|
public void RemovePlaylist(Playlist playlist)
|
|
{
|
|
playlist.PlaylistUpdated -= OnPlaylistUpdated;
|
|
_playlists.Remove(playlist);
|
|
|
|
playlistRepository.Delete(playlist);
|
|
|
|
PlaylistRemoved?.Invoke(this, new(playlist));
|
|
}
|
|
|
|
public Playlist? GetPlaylist(PlaylistSong playlistSong)
|
|
{
|
|
return _playlists.FirstOrDefault(playlist => playlist.Songs.Any(song => song.UID == playlistSong.UID));
|
|
}
|
|
|
|
private async void OnPlaylistUpdated(object? sender, PlaylistUpdatedEventArgs e)
|
|
{
|
|
if (sender is not Playlist playlist)
|
|
return;
|
|
|
|
await playlistRepository.SaveAsync(playlist);
|
|
}
|
|
} |