Commit 36de9b34 authored by Nina Rybárová's avatar Nina Rybárová
Browse files

added notes providing service

parent 98c97045
Loading
Loading
Loading
Loading
+10 −0
Original line number Original line Diff line number Diff line
import 'package:adnotes/notes/service/notes_providing_service.dart';
import 'package:get_it/get_it.dart';

final get = GetIt.instance;

class IocContainer {
  void setup() {
    get.registerSingleton<NotesProvidingService>(NotesProvidingService());
  }
}
+64 −0
Original line number Original line Diff line number Diff line
import 'dart:convert';
import 'dart:io';
import 'package:adnotes/common/model/note.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';

const _NOTES_DIRECTORY = 'AdNotesData';
const _NOTES_FILE_NAME = 'ad_notes.json';

class NotesProvidingService {
  NotesProvidingService();

  Future<void> saveNote(Note note) async {
    final file = await _getNotesFile();
    await file.create(recursive: true);

    final notes = await loadNotes();
    notes.add(note);

    final jsonContent = jsonEncode(notes.map((n) => n.toJson()).toList());
    await file.writeAsString(jsonContent);
  }

  Future<void> updateNote(String id, Note note) async {
    final notes = await loadNotes();

    final index = notes.indexWhere((note) => note.id == id);
    if (index != -1) {
      notes[index] = note;
    }

    final presetsJson = jsonEncode(notes.map((e) => e.toJson()).toList());
    final file = await _getNotesFile();
    await file.writeAsString(presetsJson);
  }

  Future<void> deleteNoteById(String id) async {
    final notes = await loadNotes();
    notes.removeWhere((n) => n.id == id);
    final file = await _getNotesFile();
    await file.writeAsString(jsonEncode(notes.map((n) => n.toJson()).toList()));
  }

  Future<List<Note>> loadNotes() async {
    final file = await _getNotesFile();
    if (!await file.exists()) return [];

    final content = await file.readAsString();
    if (content.isEmpty) return [];

    final List<dynamic> jsonList = jsonDecode(content);
    return jsonList.map((json) => Note.fromJson(json)).toList();
  }

  Future<File> _getNotesFile() async {
    final dirPath = await _getNotesDirectoryPath();
    return File(p.join(dirPath, _NOTES_FILE_NAME));
  }

  Future<String> _getNotesDirectoryPath() async {
    final appDocumentsDirectory = await getApplicationDocumentsDirectory();
    return p.join(appDocumentsDirectory.path, _NOTES_DIRECTORY);
  }
}