// Copyright 2020 Ben Hills. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:pinepods_mobile/entities/persistable.dart'; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; class PersistentState { static Future persistState(Persistable persistable) async { var d = await getApplicationSupportDirectory(); var file = File(join(d.path, 'state.json')); var sink = file.openWrite(); var json = jsonEncode(persistable.toMap()); sink.write(json); await sink.flush(); await sink.close(); } static Future fetchState() async { var d = await getApplicationSupportDirectory(); var file = File(join(d.path, 'state.json')); var p = Persistable.empty(); if (file.existsSync()) { var result = file.readAsStringSync(); if (result.isNotEmpty) { var data = jsonDecode(result) as Map; p = Persistable.fromMap(data); } } return Future.value(p); } static Future clearState() async { var file = await _getFile(); if (file.existsSync()) { file.delete(); } } static Future writeInt(String name, int value) async { return _writeValue(name, value.toString()); } static Future readInt(String name) async { var result = await _readValue(name); return result.isEmpty ? 0 : int.parse(result); } static Future writeString(String name, String value) async { return _writeValue(name, value); } static Future readString(String name) async { return _readValue(name); } static Future _readValue(String name) async { var d = await getApplicationSupportDirectory(); var file = File(join(d.path, name)); var result = file.readAsStringSync(); return result; } static Future _writeValue(String name, String value) async { var d = await getApplicationSupportDirectory(); var file = File(join(d.path, name)); var sink = file.openWrite(); sink.write(value.toString()); await sink.flush(); await sink.close(); } static Future _getFile() async { var d = await getApplicationSupportDirectory(); return File(join(d.path, 'state.json')); } }