import 'package:flutter/material.dart';
import 'package:nextcloud/nextcloud.dart';

import '../api/marianumcloud/webdav/webdav_api.dart';
import '../widget/confirm_dialog.dart';
import 'remote_file_ref.dart';

/// Server-side WebDAV copy of [source] into [targetFolderPath]. On a 412
/// conflict the user is asked whether to overwrite; on confirmation the call
/// is retried with `overwrite: true`. Returns true when the file ended up at
/// the target, false when the user cancelled.
Future<bool> copyRemoteFileTo({
  required BuildContext context,
  required RemoteFileRef source,
  required String targetFolderPath,
}) async {
  final webdav = await WebdavApi.webdav;
  final dst = targetFolderPath.isEmpty
      ? source.name
      : '${targetFolderPath.replaceAll(RegExp(r'/+$'), '')}/${source.name}';
  final src = PathUri.parse(source.path);
  final dstUri = PathUri.parse(dst);

  try {
    await webdav.copy(src, dstUri);
    return true;
  } on DynamiteApiException catch (e) {
    if (e.statusCode != 412) rethrow;
    if (!context.mounted) return false;
    final overwrite = await showDialog<bool>(
      context: context,
      builder: (ctx) => ConfirmDialog(
        title: 'Datei existiert bereits',
        content:
            '"${source.name}" existiert in /$targetFolderPath. Überschreiben?',
        confirmButton: 'Überschreiben',
        cancelButton: 'Abbrechen',
        onConfirm: () => Navigator.of(ctx).pop(true),
      ),
    );
    if (overwrite != true) return false;
    await webdav.copy(src, dstUri, overwrite: true);
    return true;
  }
}
