handleDelete method

Future<void> handleDelete(
  1. BuildContext context
)

Handles file deletion from the POD.

Implementation

Future<void> handleDelete(BuildContext context) async {
  if (state.remoteFileName == null || state.currentPath == null) return;

  try {
    state = state.copyWith(deleteInProgress: true, deleteDone: false);

    final baseDir = basePath;
    final filePath = state.currentPath == baseDir
        ? '$baseDir/${state.remoteFileName}'
        : '${state.currentPath}/${state.remoteFileName}';

    // debugPrint('Attempting to delete file at path: $filePath');

    if (!context.mounted) return;

    // First try to delete the main file.

    bool mainFileDeleted = false;
    try {
      await deleteFile(filePath);
      mainFileDeleted = true;
      // debugPrint('Successfully deleted main file: $filePath');
    } catch (e) {
      debugPrint('Error deleting main file: $e');
      // Only rethrow if it's not a 404 error.

      if (!e.toString().contains('404') &&
          !e.toString().contains('NotFoundHttpError')) {
        rethrow;
      }
    }

    if (!context.mounted) return;

    // If main file deletion succeeded, try to delete the ACL file.

    if (mainFileDeleted) {
      try {
        await deleteFile('$filePath.acl');
        // debugPrint('Successfully deleted ACL file');
      } catch (e) {
        // ACL files are optional and may not exist.

        if (e.toString().contains('404') ||
            e.toString().contains('NotFoundHttpError')) {
          debugPrint('ACL file not found (safe to ignore)');
        } else {
          debugPrint('Error deleting ACL file: ${e.toString()}');
        }
      }

      if (!context.mounted) return;
      state = state.copyWith(deleteDone: true);

      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('File deleted successfully'),
            backgroundColor: Theme.of(context).colorScheme.tertiary,
          ),
        );

        // Call the refresh callback to update the browser.

        _refreshCallback?.call();
      }
    }
  } catch (e) {
    if (!context.mounted) return;

    state = state.copyWith(deleteDone: false);

    // Provide user-friendly error messages.

    final message = e.toString().contains('404') ||
            e.toString().contains('NotFoundHttpError')
        ? 'File not found or already deleted'
        : 'Delete failed: ${e.toString()}';

    showAlert(context, message);
    debugPrint('Delete error: $e');
  } finally {
    if (context.mounted) {
      state = state.copyWith(deleteInProgress: false);
    }
  }
}