//
//  StorageManager.swift
//  PhoneManager
//
//  Created by edy on 2025/4/28.
//

import Foundation
import Photos
import Darwin

class StorageManager {
    
    static let manager : StorageManager = StorageManager()
    
    // 获取照片内存
    func getPhotoResourceMemory() async -> Double {
        return await withCheckedContinuation { continuation in
            PHPhotoLibrary.requestAuthorization(for: .readWrite) { status in
                switch status {
                case .authorized:
                    Task {
                        var totalSize: UInt64 = 0
                        let options = PHFetchOptions()
                        let fetchResult = PHAsset.fetchAssets(with: .image, options: options)
                        fetchResult.enumerateObjects { (asset, _, _) in
                            let resources = PHAssetResource.assetResources(for: asset)
                            for resource in resources {
                                if let fileSize = resource.value(forKey: "fileSize") as? UInt64 {
                                    totalSize += fileSize
                                }
                            }
                        }
                        let result = Double(totalSize)
                        continuation.resume(returning: result)
                    }
                case .denied, .restricted:
                    print("没有权限访问照片库")
                    continuation.resume(returning: 0)
                case .notDetermined, .limited:
                    print("照片库权限未确定或受限")
                    continuation.resume(returning: 0)
                @unknown default:
                    print("未知的照片库权限状态")
                    continuation.resume(returning: 0)
                }
            }
        }
    }
}
