using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Input;
using PSCHelpdesk.Shared.Service;
using PSCHelpdesk.Shared.ViewModels;
using PSCHelpdesk.Toasts.Display;

namespace PSCHelpdesk.Toasts;

public class ToastManager: ViewModelBase,IToastManager
{
    private ObservableCollection<ToastNotificationViewModel> _notifications;

    public ObservableCollection<ToastNotificationViewModel> Notifications
    {
        get => this._notifications;
        private set => SetAndRaisePropertyChanged(ref _notifications, value);
    }
    
    public int MaximumNotifications { get; set; } = 5;
    
    public TimeSpan AutomaticDismissalTime { get; set; } = TimeSpan.FromSeconds(7);

    private List<Task> DismissalTasks { get; }

    public EventHandler OnAdd;
    
    public ToastManager()
    {
        this.Notifications = new ObservableCollection<ToastNotificationViewModel>() { };
        this.DismissalTasks = new List<Task>();
    }
    
    public void DisplayNewToast(string message)
    {
        var notification = new ToastNotificationViewModel(message);
        notification.CloseAction = new RelayCommand<ToastNotificationViewModel>(this.CloseToast);
        this.Notifications.Add(notification);
        OnAdd?.Invoke(this, EventArgs.Empty);
        this.DismissalTasks.Add(this.DelayedDismissal(notification));

        Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
        {
            while (this.Notifications.Count > this.MaximumNotifications)
            {
                //this.Notifications.RemoveAt(this.Notifications.Count - 1);
            }
        });
    }
    
    private void CloseToast(ToastNotificationViewModel notification)
    {
        Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
        {
            this.Notifications.Remove(notification);
        });
    }
    
    
    private async Task DelayedDismissal(ToastNotificationViewModel toast)
    {
        await Task.Delay(this.AutomaticDismissalTime);
        this.CloseToast(toast);
    }
}