//
//  ICCameraThumbnailLoader.swift
//  otg_swift
//

import Foundation
@preconcurrency import ImageCaptureCore

/// 通过 ImageCaptureCore 请求相机内文件的缩略图 Data。
enum ICCameraThumbnailLoader {

    static func loadThumbnailData(
        for object: CameraObject,
        from device: ICCameraDevice,
        maxPixelSize: Int
    ) async -> Data? {
        guard let file = ICCameraItemScanner.findFile(matching: object, in: device) else {
            return nil
        }
        return await loadThumbnailData(from: file, maxPixelSize: maxPixelSize)
    }

    /// `maxPixelSize` 控制缩略图最长边像素，用于导入网格展示。
    static func loadThumbnailData(from file: ICCameraFile, maxPixelSize: Int) async -> Data? {
        await withCheckedContinuation { continuation in
            let options: [ICCameraItemThumbnailOption: Any] = [
                ICCameraItemThumbnailOption.imageSourceThumbnailMaxPixelSize: maxPixelSize
            ]

            file.requestThumbnailData(options: options) { data, error in
                if let error {
                    OTGLog.debug(.connection, "thumbnail failed for \(file.name ?? "nil"): \(error.localizedDescription)")
                    continuation.resume(returning: nil)
                    return
                }
                continuation.resume(returning: data)
            }
        }
    }
}
