using Harmonia.Core.Data;

namespace Harmonia.Core.Playlists;

public class PlaylistRepository : JsonFileRepository<Playlist>, IPlaylistRepository
{
    protected override string DirectoryName => Path.Combine("Playlists");

    public PlaylistRepository()
    {
        List<Playlist> playlists = Get();

        foreach (Playlist playlist in playlists)
        {
            playlist.PlaylistUpdated += OnPlaylistUpdated;
        }

        if (playlists.Count == 0)
            AddPlaylist();
    }

    private void OnPlaylistUpdated(object? sender, PlaylistUpdatedEventArgs e)
    {
        if (sender is not Playlist playlist)
            return;

        Save(playlist);
    }

    public Playlist? GetPlaylist(PlaylistSong playlistSong)
    {
        return Get().FirstOrDefault(playlist => playlist.Songs.Contains(playlistSong));
    }

    protected override string GetNewFileName()
    {
        for (int i = 0; i < 1000; i++)
        {
            string shortFileName = $"Playlist{i.ToString().PadLeft(3, '0')}.{Extension}";
            string filePath = Path.Combine(DirectoryName, shortFileName);

            if (File.Exists(filePath) == false)
                return shortFileName;
        }

        throw new Exception("Unable to determine new fileName");
    }

    public event EventHandler<PlaylistAddedEventArgs>? PlaylistAdded;
    public event EventHandler<PlaylistRemovedEventArgs>? PlaylistRemoved;

    public void AddPlaylist()
    {
        Playlist playlist = new()
        {
            Name = "New Playlist"
        };

        playlist.PlaylistUpdated += OnPlaylistUpdated;

        Save(playlist);
        PlaylistAdded?.Invoke(this, new(playlist));
    }

    public void RemovePlaylist(Playlist playlist)
    {
        playlist.PlaylistUpdated -= OnPlaylistUpdated;

        Delete(playlist);
        PlaylistRemoved?.Invoke(this, new(playlist));
    }
}