using CommunityToolkit.Mvvm.Input; using Jugenddienst_Stunden.Models; using System.Collections.ObjectModel; using System.Windows.Input; namespace Jugenddienst_Stunden.ViewModels; internal class NotesViewModel : IQueryAttributable { public ObservableCollection AllNotes { get; } public ICommand NewCommand { get; } public ICommand SelectNoteCommand { get; } public NotesViewModel() { AllNotes = new ObservableCollection(Models.Note.LoadAll().Select(n => new NoteViewModel(n))); NewCommand = new AsyncRelayCommand(NewNoteAsync); SelectNoteCommand = new AsyncRelayCommand(SelectNoteAsync); } private async Task NewNoteAsync() { await Shell.Current.GoToAsync(nameof(Views.NotePage)); } private async Task SelectNoteAsync(NoteViewModel? note) { if (note != null) await Shell.Current.GoToAsync($"{nameof(Views.NotePage)}?load={note.Identifier}"); } void IQueryAttributable.ApplyQueryAttributes(IDictionary query) { if (query.ContainsKey("deleted")) { string? noteId = query["deleted"]?.ToString(); if (noteId != null) { NoteViewModel? matchedNote = AllNotes.Where((n) => n.Identifier == noteId).FirstOrDefault(); // If note exists, delete it if (matchedNote != null) AllNotes.Remove(matchedNote); } } else if (query.ContainsKey("saved")) { string? noteId = query["saved"]?.ToString(); if (noteId != null) { NoteViewModel? matchedNote = AllNotes.FirstOrDefault((n) => n.Identifier == noteId); // If note is found, update it if (matchedNote != null) { matchedNote.Reload(); AllNotes.Move(AllNotes.IndexOf(matchedNote), 0); } // If note isn't found, it's new; add it. else { AllNotes.Insert(0, new NoteViewModel(Note.Load(noteId))); } } } } }