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> listWallets() async { final path = Directory("${(await getApplicationDocumentsDirectory()).path}/wallets"); if (!path.existsSync()) { path.createSync(); } final wallets = []; 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 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 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, ); } /// Converts [Wallet] to JSON and saves it to AppData static Future 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 deleteWallet(Wallet w) async { final path = Directory("${(await getApplicationDocumentsDirectory()).path}/wallets"); File("${path.path}/${w.name}").deleteSync(); } }