uploadJsonToPod function

Future<SolidFunctionCallStatus> uploadJsonToPod({
  1. required Map<String, dynamic> data,
  2. required String targetPath,
  3. required String fileNamePrefix,
  4. required BuildContext context,
  5. void onProgressChange(
    1. bool
    )?,
  6. void onSuccess()?,
})

Creates a temporary JSON file and uploads it to POD.

Useful for saving structured data like survey responses.

Implementation

Future<SolidFunctionCallStatus> uploadJsonToPod({
  required Map<String, dynamic> data,
  required String targetPath,
  required String fileNamePrefix,
  required BuildContext context,
  void Function(bool)? onProgressChange,
  void Function()? onSuccess,
}) async {
  late Directory tempDir;
  late File tempFile;

  try {
    // Create temp file with JSON content.

    final timestamp = formatTimestampForFilename(
        DateTime.now()); // Format timestamp for file name.
    final fileName = '${fileNamePrefix}_$timestamp.json';

    tempDir = await Directory.systemTemp.createTemp('healthpod_temp');
    tempFile = File('${tempDir.path}/$fileName');

    // Write formatted JSON.

    final jsonString = const JsonEncoder.withIndent('  ').convert(data);
    await tempFile.writeAsString(jsonString);

    // Guard against using context across async gaps.

    if (!context.mounted) {
      debugPrint('Widget is no longer mounted, skipping upload.');
      return SolidFunctionCallStatus.fail;
    }

    // Upload the file.

    return await uploadFileToPod(
      filePath: tempFile.path,
      targetPath: targetPath,
      context: context,
      onProgressChange: onProgressChange,
      onSuccess: onSuccess,
    );
  } finally {
    // Clean up temp files.

    try {
      if (tempFile.existsSync()) await tempFile.delete();
      if (tempDir.existsSync()) await tempDir.delete();
    } catch (e) {
      debugPrint('Error cleaning up temp files: $e');
    }
  }
}