import 'dart:io';
import 'dart:typed_data';

import 'package:file_picker/file_picker.dart';

import 'file_service.dart';

/// [FileService] backed by the `file_picker` plugin (one plugin covers the
/// save and open dialogs on Android, iOS and desktop).
class FilePickerFileService implements FileService {
  const FilePickerFileService();

  @override
  Future<String?> saveFile({
    required String suggestedName,
    required Uint8List bytes,
  }) async {
    final path = await FilePicker.platform.saveFile(
      fileName: suggestedName,
      bytes: bytes,
    );
    if (path == null) return null;
    // On mobile the plugin writes [bytes] itself; on desktop it only returns
    // the chosen path, so write them here.
    if (!Platform.isAndroid && !Platform.isIOS) {
      await File(path).writeAsBytes(bytes, flush: true);
    }
    return path;
  }

  @override
  Future<Uint8List?> pickFileBytes({List<String>? allowedExtensions}) async {
    final result = await FilePicker.platform.pickFiles(
      type: allowedExtensions == null ? FileType.any : FileType.custom,
      allowedExtensions: allowedExtensions,
      withData: true,
    );
    final file = result?.files.singleOrNull;
    if (file == null) return null;
    // withData should populate bytes; fall back to the path just in case.
    final bytes = file.bytes;
    if (bytes != null) return bytes;
    final path = file.path;
    if (path == null) return null;
    return File(path).readAsBytes();
  }
}
