using System.Windows.Threading;
using NexusShell.Models;

namespace NexusShell.Services;

public sealed class NexusSlideshowService : IDisposable
{
    private readonly DispatcherTimer _timer;
    private IReadOnlyList<NexusPhotoItem> _items = [];
    private int _currentIndex;

    public NexusSlideshowService()
    {
        _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
        _timer.Tick += (_, _) => Advance();
    }

    public event EventHandler? StateChanged;

    public bool IsActive { get; private set; }
    public NexusPhotoItem? CurrentPhoto => IsActive && _items.Count > 0 ? _items[_currentIndex] : null;
    public string PositionLabel => _items.Count == 0 ? "0 / 0" : $"{_currentIndex + 1} / {_items.Count}";

    public void Start(IReadOnlyList<NexusPhotoItem> items, int startIndex)
    {
        if (items.Count == 0)
        {
            return;
        }

        _items = items;
        _currentIndex = Math.Clamp(startIndex, 0, items.Count - 1);
        IsActive = true;
        _timer.Start();
        NotifyChanged();
    }

    public void Stop()
    {
        _timer.Stop();
        IsActive = false;
        NotifyChanged();
    }

    public void Advance()
    {
        if (_items.Count == 0)
        {
            return;
        }

        _currentIndex = (_currentIndex + 1) % _items.Count;
        NotifyChanged();
    }

    public void GoPrevious()
    {
        if (_items.Count == 0)
        {
            return;
        }

        _currentIndex = (_currentIndex - 1 + _items.Count) % _items.Count;
        NotifyChanged();
    }

    public void GoNext() => Advance();

    public void Dispose() => _timer.Stop();

    private void NotifyChanged() => StateChanged?.Invoke(this, EventArgs.Empty);
}
