From e6c2d4149defe1dbe4e836a00ca887e28361b918 Mon Sep 17 00:00:00 2001
From: vjrj <vjrj@comunes.org>
Date: Sun, 20 Aug 2023 13:44:34 +0200
Subject: [PATCH] More work with multi-card support

---
 assets/translations/en.json                   |  2 ++
 assets/translations/es.json                   |  1 +
 lib/shared_prefs_helper.dart                  | 10 +++---
 lib/ui/widgets/cesium_auth_dialog.dart        | 19 ++++++-----
 .../widgets/fifth_screen/import_dialog.dart   | 34 +++++++++++--------
 .../first_screen/card_name_editable.dart      |  4 +--
 6 files changed, 41 insertions(+), 29 deletions(-)

diff --git a/assets/translations/en.json b/assets/translations/en.json
index 082ece30..e2e49caf 100644
--- a/assets/translations/en.json
+++ b/assets/translations/en.json
@@ -208,6 +208,8 @@
   "select_import_method": "Select Import Method",
   "file_import": "Import from File",
   "export": "EXPORT",
+  "clipboard_import": "Import from Clipboard",
+  "clipboard_import_pubkey": "Import from public key",
   "clipboard_export": "Export to Clipboard",
   "select_export_method": "Select Export Method",
   "file_export": "Export to File",
diff --git a/assets/translations/es.json b/assets/translations/es.json
index 83317293..c60f18ac 100644
--- a/assets/translations/es.json
+++ b/assets/translations/es.json
@@ -210,6 +210,7 @@
   "select_import_method": "Selecciona el método de importación",
   "file_import": "Importar desde archivo",
   "clipboard_import": "Importar desde portapapeles",
+  "clipboard_import_pubkey": "Importar desde clave pública",
   "export": "EXPORTAR",
   "clipboard_export": "Exportar al portapapeles",
   "select_export_method": "Selecciona el método de exportación",
diff --git a/lib/shared_prefs_helper.dart b/lib/shared_prefs_helper.dart
index 49c3a8f2..29b7e6ed 100644
--- a/lib/shared_prefs_helper.dart
+++ b/lib/shared_prefs_helper.dart
@@ -81,11 +81,13 @@ class SharedPreferencesHelper with ChangeNotifier {
     }
   }
 
-  Future<void> saveCesiumCards() async {
+  Future<void> saveCesiumCards([bool notify = true]) async {
     final String json =
         jsonEncode(cesiumCards.map((CesiumCard e) => e.toJson()).toList());
     await _prefs.setString('cesiumCards', json);
-    notifyListeners();
+    if (notify) {
+      notifyListeners();
+    }
   }
 
   // Get the wallet from the specified index (default to first wallet)
@@ -126,10 +128,10 @@ class SharedPreferencesHelper with ChangeNotifier {
     return card.theme;
   }
 
-  void setName({required String name}) {
+  void setName({required String name, bool notify = true}) {
     final CesiumCard card = cesiumCards[getCurrentWalletIndex()];
     cesiumCards[getCurrentWalletIndex()] = card.copyWith(name: name);
-    saveCesiumCards();
+    saveCesiumCards(notify);
   }
 
   void setTheme({required CreditCardTheme theme}) {
diff --git a/lib/ui/widgets/cesium_auth_dialog.dart b/lib/ui/widgets/cesium_auth_dialog.dart
index da59e5fa..6312824c 100644
--- a/lib/ui/widgets/cesium_auth_dialog.dart
+++ b/lib/ui/widgets/cesium_auth_dialog.dart
@@ -16,10 +16,8 @@ import '../ui_helpers.dart';
 import 'form_error_widget.dart';
 
 class CesiumAddDialog extends StatefulWidget {
-  const CesiumAddDialog(
-      {super.key, required this.cardName, required this.publicKey});
+  const CesiumAddDialog({super.key, required this.publicKey});
 
-  final String cardName;
   final String publicKey;
 
   @override
@@ -41,17 +39,20 @@ class _CesiumAddDialogState extends State<CesiumAddDialog> {
       builder: (BuildContext context, AsyncSnapshot<Contact> snapshot) {
         if (snapshot.hasData) {
           return showDialog(
-              context, humanizeContact(widget.publicKey, snapshot.data!));
+            context,
+            snapshot.data!,
+          );
         }
-        return showDialog(context, humanizePubKey(widget.publicKey));
+        return showDialog(context, Contact(pubKey: widget.publicKey));
       },
     );
   }
 
-  AlertDialog showDialog(BuildContext context, String name) {
+  AlertDialog showDialog(BuildContext context, Contact contact) {
     return AlertDialog(
-      title: Text(tr('cesium_auth_dialog_title',
-          namedArgs: <String, String>{'key': name})),
+      title: Text(tr('cesium_auth_dialog_title', namedArgs: <String, String>{
+        'key': humanizeContact(widget.publicKey, contact)
+      })),
       content: SingleChildScrollView(
         child: ListBody(
           children: <Widget>[
@@ -126,7 +127,7 @@ class _CesiumAddDialogState extends State<CesiumAddDialog> {
                     _feedbackNotifier.value = tr('incorrect_passwords');
                   } else {
                     final CesiumCard card = CesiumCard(
-                        name: widget.cardName,
+                        name: contact.name ?? '',
                         pubKey: extractPublicKey(widget.publicKey),
                         seed: '',
                         theme: CreditCardThemes.themes[Random().nextInt(10)]);
diff --git a/lib/ui/widgets/fifth_screen/import_dialog.dart b/lib/ui/widgets/fifth_screen/import_dialog.dart
index 843b2803..a0d50d25 100644
--- a/lib/ui/widgets/fifth_screen/import_dialog.dart
+++ b/lib/ui/widgets/fifth_screen/import_dialog.dart
@@ -45,7 +45,7 @@ class _ImportDialogState extends State<ImportDialog> {
               snapshot.data!.isNotEmpty) {
             final String keyEncString = snapshot.data!;
             final Map<String, dynamic> keyJson =
-                jsonDecode(keyEncString) as Map<String, dynamic>;
+            jsonDecode(keyEncString) as Map<String, dynamic>;
             final String keyEncrypted = keyJson['key'] as String;
             // final Uint8List keyBase64 = base64Decode(keyEncrypted);
             return Scaffold(
@@ -74,16 +74,16 @@ class _ImportDialogState extends State<ImportDialog> {
                         try {
                           // try to decrypt
                           final Map<String, dynamic> keys =
-                              decryptJsonForImport(
-                                  keyEncrypted, pattern.join());
+                          decryptJsonForImport(
+                              keyEncrypted, pattern.join());
                           final bool? confirm = await confirmImport(context);
                           if (confirm != null && confirm) {
                             try {
                               final dynamic cesiumCards = keys['cesiumCards'];
                               if (cesiumCards != null) {
                                 final List<dynamic> cesiumCardList =
-                                    jsonDecode(cesiumCards as String)
-                                        as List<dynamic>;
+                                jsonDecode(cesiumCards as String)
+                                as List<dynamic>;
                                 // ignore: avoid_function_literals_in_foreach_calls
                                 cesiumCardList.forEach((dynamic cesiumCard) {
                                   importWalletToSharedPrefs(
@@ -152,9 +152,9 @@ class _ImportDialogState extends State<ImportDialog> {
     final dynamic pub = cesiumCard['pub'];
     SharedPreferencesHelper().addCesiumCard(SharedPreferencesHelper()
         .buildCesiumCard(
-            pubKey:
-                pub != null ? pub as String : cesiumCard['pubKey'] as String,
-            seed: cesiumCard['seed'] as String));
+        pubKey:
+        pub != null ? pub as String : cesiumCard['pubKey'] as String,
+        seed: cesiumCard['seed'] as String));
   }
 
   Future<String> _importWallet(BuildContext context) async {
@@ -212,7 +212,8 @@ class _ImportDialogState extends State<ImportDialog> {
 
   Future<String> _importWalletWeb(BuildContext context) async {
     final Completer<String> completer = Completer<String>();
-    final html.InputElement input = html.InputElement()..type = 'file';
+    final html.InputElement input = html.InputElement()
+      ..type = 'file';
 
     input.multiple = false;
     input.accept = '.json'; // limit file types
@@ -247,7 +248,9 @@ class _ImportDialogState extends State<ImportDialog> {
   }
 
   Future<bool?> confirmImport(BuildContext context) async {
-    final bool hasBalance = context.read<TransactionCubit>().balance > 0;
+    final bool hasBalance = context
+        .read<TransactionCubit>()
+        .balance > 0;
     return showDialog<bool>(
       context: context,
       builder: (BuildContext context) {
@@ -311,14 +314,13 @@ Future<void> showSelectImportMethodDialog(BuildContext context) async {
   }
 }
 
-Future<bool?> showImportCesiumWalletDialog(
-    BuildContext context, String wallet) {
+Future<bool?> showImportCesiumWalletDialog(BuildContext context,
+    String wallet) {
   return showDialog<bool>(
     context: context,
     barrierDismissible: false,
     builder: (BuildContext dialogContext) {
-      return CesiumAddDialog(
-          cardName: humanizePubKey(wallet), publicKey: wallet);
+      return CesiumAddDialog(publicKey: wallet);
     },
   );
 }
@@ -340,6 +342,10 @@ class SelectImportMethodDialog extends StatelessWidget {
             icon: const Icon(Icons.content_paste),
             label: Text(tr('clipboard_import')),
             onPressed: () => Navigator.of(context).pop('clipboard')),
+        TextButton.icon(
+            icon: const Icon(Icons.key),
+            label: Text(tr('clipboard_import_pubkey')),
+            onPressed: () => Navigator.of(context).pop('clipboard')),
       ],
     );
   }
diff --git a/lib/ui/widgets/first_screen/card_name_editable.dart b/lib/ui/widgets/first_screen/card_name_editable.dart
index 4dc96a9a..ce5b8c65 100644
--- a/lib/ui/widgets/first_screen/card_name_editable.dart
+++ b/lib/ui/widgets/first_screen/card_name_editable.dart
@@ -47,11 +47,11 @@ class _CardNameEditableState extends State<CardNameEditable> {
             name = name.replaceAll(userNameSuffix, '');
             _controller.text = name;
             currentText = name;
-            // SharedPreferencesHelper().setName(name: name);
+            SharedPreferencesHelper().setName(name: name, notify: false);
           } else {
             _controller.text = '';
             currentText = widget.defValue;
-            // SharedPreferencesHelper().setName(name: '');
+            SharedPreferencesHelper().setName(name: '', notify: false);
           }
         }
       } catch (e) {
-- 
GitLab