using Avalonia.Threading;
using CommunityToolkit.Mvvm.DependencyInjection;
using PSCHelpdesk.Plugins.Nextcloud.Models;
using PSCHelpdesk.Shared.Service;
using PSCHelpdesk.Shared.Setting;

namespace PSCHelpdesk.Plugins.Nextcloud.Services;

public class NotesService
{
    public List<Note> Notes;
    private Api.Notes _notes;
    private readonly IToastManager? _toastManager;
    private SettingsManager _settingsManager;
    public EventHandler OnNotesChanged;
    private DispatcherTimer _timer;
    public NotesService()
    {
        Notes = new List<Note>();
        _settingsManager = (SettingsManager)Ioc.Default.GetService<ISettingsManager>();
        _toastManager = (IToastManager)Ioc.Default.GetService<IToastManager>();
        _notes = new Api.Notes();
        
        _timer = new DispatcherTimer();
        _timer.Interval = TimeSpan.FromMinutes(10);
        _timer.Tick += async (_, _) => LoadNotes();
        _timer.Start();
    }

    public async Task LoadNotes()
    {
        var settings = new Settings();
        _settingsManager.LoadPluginSettings("NextcloudSettings", settings);

        if (settings.AppPassword != "")
        {
            _toastManager.DisplayNewToast("Reload Notes started");
            Notes = await _notes.GetNotes(settings);
            _toastManager.DisplayNewToast("Reload Notes finshed");
            this.OnNotesChanged.Invoke(null, EventArgs.Empty);
        }
    }
    
}