using Avalonia.Controls;
using Harmonia.Core.Engine;
using Harmonia.Core.Models;
using Harmonia.Core.Player;
using System.ComponentModel;
using System.Linq;

namespace Harmonia.UI.Views;

public partial class MainWindow : Window
{
    private readonly IAudioPlayer _audioPlayer;

    private const string ApplicationTitle = "Harmonia";

    public MainWindow(IAudioPlayer audioPlayer)
    {
        _audioPlayer = audioPlayer;
        _audioPlayer.PropertyChanged += OnAudioPlayerPropertyChanged;

        Title = ApplicationTitle;

        InitializeComponent();
    }

    private void OnAudioPlayerPropertyChanged(object? sender, PropertyChangedEventArgs e)
    {
        switch (e.PropertyName)
        {
            case nameof(_audioPlayer.State):
                Title = GetUpdatedAppTitle();
                //PropertyChanged(nameof(Title));
                break;
        }
    }

    private string GetUpdatedAppTitle()
    {
        return _audioPlayer.State switch
        {
            AudioPlaybackState.Stopped => ApplicationTitle,
            _ => $"{GetSongArtistsAndTitle()} - {ApplicationTitle}"
        };
    }

    private string GetSongArtistsAndTitle()
    {
        if (_audioPlayer.PlayingSong == null)
            return string.Empty;

        Song song = _audioPlayer.PlayingSong.Song;

        string[] values =
        [
            string.Join(" / ", song.Artists ?? song.AlbumArtists),
            song.Title ?? song.ShortFileName
        ];

        return string.Join(" - ", values.Where(value => string.IsNullOrWhiteSpace(value) == false));
    }
}
