using System.Windows.Input;
using CommunityToolkit.Mvvm.DependencyInjection;
using PSCHelpdesk.Plugins.Nextcloud.Models;
using PSCHelpdesk.Plugins.Nextcloud.Services;
using PSCHelpdesk.Shared.Service;
using PSCHelpdesk.Shared.ViewModels;
using ReactiveUI;

namespace PSCHelpdesk.Plugins.Nextcloud.ViewModels;
          
public partial class NotesViewModel: ViewModelBase, IViewModelBase
{
    public ICommand SelectNote { get; }
    
    private List<Note> _notes;
    public List<Note> Notes
    {
        get => _notes;
        set => this.SetAndRaisePropertyChanged(ref _notes, value);
    }
    
    private Note _selectedNote;
    public Note SelectedNote
    {
        get => _selectedNote;
        set => this.SetAndRaisePropertyChanged(ref _selectedNote, value);
    }
    
    private NotesService _notesService;
    

    public NotesViewModel()
    {
        Title = "Notes";
        SelectedNote = new Note();
        Notes = new List<Note>();
        _notesService = new NotesService();
        _notesService.OnNotesChanged += (sender, args) => this.reloadNotes();
        _notesService.LoadNotes();
        SelectNote = ReactiveCommand.Create((Note note) =>
        {
            selectNote(note);
        });
    }

    private void reloadNotes()
    {
        Notes = _notesService.Notes;
    }

    private async void selectNote(Note note)
    {
        var uiDispatcher = Ioc.Default.GetService<IUserInterfaceDispatchService>();
        await uiDispatcher.InvokeAsync(() =>
        {
            SelectedNote = note;
        });
    }
}