mirror of
https://github.com/cyberbread-ru/notepad.git
synced 2026-07-14 12:51:01 +03:00
94 lines
2.7 KiB
Dart
94 lines
2.7 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
|
|
import '../models/note.dart';
|
|
import '../services/note_service.dart';
|
|
|
|
enum BackupStatus { idle, loading, success, error }
|
|
|
|
class NoteViewModel extends ChangeNotifier {
|
|
final NoteService _service;
|
|
|
|
NoteViewModel({required NoteService service}) : _service = service;
|
|
|
|
List<Note> _notes = [];
|
|
bool _isLoading = false;
|
|
String? _error;
|
|
BackupStatus _backupStatus = BackupStatus.idle;
|
|
|
|
// ── Getters ────────────────────────────────────────────────
|
|
List<Note> get notes => _notes;
|
|
bool get isLoading => _isLoading;
|
|
String? get error => _error;
|
|
BackupStatus get backupStatus => _backupStatus;
|
|
|
|
// ── Notes CRUD ─────────────────────────────────────────────
|
|
Future<void> loadNotes() async {
|
|
_setLoading(true);
|
|
try {
|
|
_notes = await _service.getAllNotes();
|
|
_error = null;
|
|
} catch (e) {
|
|
_error = 'Failed to load notes: $e';
|
|
} finally {
|
|
_setLoading(false);
|
|
}
|
|
}
|
|
|
|
Future<Note> createNote() async {
|
|
final note = await _service.createNote();
|
|
_notes.insert(0, note);
|
|
notifyListeners();
|
|
return note;
|
|
}
|
|
|
|
Future<void> updateNote(Note note) async {
|
|
final updated = await _service.updateNote(note);
|
|
final index = _notes.indexWhere((n) => n.id == updated.id);
|
|
if (index != -1) {
|
|
_notes[index] = updated;
|
|
notifyListeners();
|
|
}
|
|
}
|
|
|
|
Future<void> deleteNote(String id) async {
|
|
await _service.deleteNote(id);
|
|
_notes.removeWhere((n) => n.id == id);
|
|
notifyListeners();
|
|
}
|
|
|
|
// ── Backup ─────────────────────────────────────────────────
|
|
Future<void> backup() async {
|
|
_setBackupStatus(BackupStatus.loading);
|
|
try {
|
|
await _service.triggerBackup();
|
|
_setBackupStatus(BackupStatus.success);
|
|
} catch (e) {
|
|
_error = e.toString();
|
|
_setBackupStatus(BackupStatus.error);
|
|
}
|
|
}
|
|
|
|
Future<void> restore() async {
|
|
_setBackupStatus(BackupStatus.loading);
|
|
try {
|
|
await _service.triggerRestore();
|
|
await loadNotes();
|
|
_setBackupStatus(BackupStatus.success);
|
|
} catch (e) {
|
|
_error = e.toString();
|
|
_setBackupStatus(BackupStatus.error);
|
|
}
|
|
}
|
|
|
|
// ── Helpers ────────────────────────────────────────────────
|
|
void _setLoading(bool value) {
|
|
_isLoading = value;
|
|
notifyListeners();
|
|
}
|
|
|
|
void _setBackupStatus(BackupStatus status) {
|
|
_backupStatus = status;
|
|
notifyListeners();
|
|
}
|
|
}
|