using System;
using Avalonia.Controls.Notifications;
using Avalonia.Threading;
using detect.gui.VWS;
using ReactiveUI;
using Splat;

namespace detect.gui.VWMS;


public class ViewModelBase<T> : ReactiveObject where T : new()
{
    private static T? _instance;

    public static T Instance()
    {
        return _instance ??= new T();
    }
    
    private bool _isLoading;
    public bool IsLoading
    {
        get => _isLoading;
        set => this.RaiseAndSetIfChanged(ref _isLoading, value);
    }
        
    private MessageItem? _message;

    public MessageItem? Message
    {
        get => _message;
        set => this.RaiseAndSetIfChanged(ref _message, value);
    }
    
    protected ViewModelBase()
    {
        this.WhenAnyValue(x => x.Message).Subscribe(m =>
        {
            if (m == null) return;
            Dispatcher.UIThread.InvokeAsync(() =>
            {
                Locator.Current.GetService<NotificationWindow>()!.IsSuccess = m.NotificationType == NotificationType.Success;
                Locator.Current.GetService<NotificationWindow>()!.IsError = m.NotificationType == NotificationType.Error;
                Locator.Current.GetService<NotificationWindow>()!.IsInformation = m.NotificationType == NotificationType.Information;
                Locator.Current.GetService<NotificationWindow>()!.IsWarning = m.NotificationType == NotificationType.Warning;
                Locator.Current.GetService<NotificationWindow>()!.Message = m.Text;
                Locator.Current.GetService<NotificationWindow>()!.Show();
                var timer = new DispatcherTimer
                {
                    Interval = TimeSpan.FromSeconds(5)
                };
                timer.Tick += (s, e) => Locator.Current.GetService<NotificationWindow>()!.Hide();
                timer.Start();
            });
        });
    }
}

public class MessageItem : ReactiveObject
{
    private readonly string? _text;
    public string? Text
    {
        get => _text;
        init => this.RaiseAndSetIfChanged(ref _text, value);
    }
        
    private readonly NotificationType _notificationType;
    public NotificationType NotificationType
    {
        get => _notificationType;
        init => this.RaiseAndSetIfChanged(ref _notificationType, value);
    }

    public MessageItem(string? text, NotificationType notificationType)
    {
        _text = text;
        _notificationType = notificationType;
    }
}