prasule/lib/api/wallet_manager.dart
Matyáš Caras 96e672f1d5 test: create basic tests (#24)
Related to #1 but more tests should be added, so not closing

Reviewed-on: #24
2024-01-22 14:41:16 +01:00

79 lines
2.3 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:prasule/api/wallet.dart';
import 'package:prasule/main.dart';
/// Used for [Wallet]-managing operations
class WalletManager {
/// Returns a list of all [Wallet]s
static Future<List<Wallet>> listWallets() async {
final path =
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
if (!path.existsSync()) {
path.createSync();
}
final wallets = <Wallet>[];
for (final w
in path.listSync().map((e) => e.path.split("/").last).toList()) {
try {
wallets.add(await loadWallet(w));
} catch (e) {
logger.e(e);
// TODO: do something with unreadable wallets
}
}
return wallets;
}
/// Deletes all [Wallet]s
static Future<void> deleteAllData() async {
final path =
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
if (!path.existsSync()) {
return;
}
for (final entry in path.listSync()) {
logger.d("Deleting ${entry.path}");
entry.deleteSync();
}
}
/// Loads and returns a single [Wallet] by name
static Future<Wallet> loadWallet(String name) async {
final path =
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
final wallet = File("${path.path}/$name");
if (!path.existsSync()) {
path.createSync();
}
if (!wallet.existsSync()) {
return Future.error("Wallet does not exist");
}
return Wallet.fromJson(
jsonDecode(wallet.readAsStringSync()) as Map<String, dynamic>,
);
}
/// Converts [Wallet] to JSON and saves it to AppData
static Future<bool> saveWallet(Wallet w) async {
final path =
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
final wallet = File("${path.path}/${w.name}");
if (!path.existsSync()) {
path.createSync();
}
// if (!wallet.existsSync()) return false;
wallet.writeAsStringSync(jsonEncode(w.toJson()));
return true;
}
/// Deletes the corresponding [Wallet] file
static Future<void> deleteWallet(Wallet w) async {
final path =
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
File("${path.path}/${w.name}").deleteSync();
}
}