mergeImportedEncryptedPlaces static method

Future<bool> mergeImportedEncryptedPlaces(
  1. List<Place> importedPlaces,
  2. BuildContext context,
  3. Widget child, {
  4. void onProgress(
    1. int current,
    2. int total
    )?,
})

Merge imported places into encrypted storage.

Implementation

static Future<bool> mergeImportedEncryptedPlaces(
  List<Place> importedPlaces,
  BuildContext context,
  Widget child, {
  void Function(int current, int total)? onProgress,
}) async {
  try {
    // Ensure security key.
    if (!await ensureSecurityKey(context, child)) {
      return false;
    }

    final existingPlaces = await fetchEncryptedPlaces();
    final existingIds = existingPlaces.map((p) => p.id).toSet();

    // Filter out duplicates.
    final newPlaces = importedPlaces
        .where((p) => !existingIds.contains(p.id))
        .toList();

    if (newPlaces.isEmpty && importedPlaces.isNotEmpty) {
      // All were duplicates.
      return true;
    }

    // Report progress.

    for (int i = 0; i < newPlaces.length; i++) {
      onProgress?.call(i + 1, newPlaces.length);
    }

    // Merge and write.
    final allPlaces = [...newPlaces, ...existingPlaces];
    return await writeEncryptedPlaces(allPlaces, context, child);
  } catch (e) {
    debugPrint('Error merging imported encrypted places: $e');
    return false;
  }
}