//
//  FileManager.swift
//  PhoneManager
//
//  Created by edy on 2025/4/27.
//

import Foundation
import Photos

struct FileTool{
    
    enum StorageType{
        case total,used,free
    }
    
    func getStorageInfo(for type: StorageType) -> Int64? {
        let fileManager = FileManager.default
        do {
            // 获取主目录的文件系统属性
            let systemAttributes = try fileManager.attributesOfFileSystem(forPath: NSHomeDirectory())
            
            // 获取总存储和可用空间
            guard let totalSize = systemAttributes[FileAttributeKey.systemSize] as? NSNumber,
                  let freeSize = systemAttributes[FileAttributeKey.systemFreeSize] as? NSNumber else {
                      return nil // 返回 nil 如果无法获取所需信息
                  }
            
            switch type {
            case .total:
                return totalSize.int64Value // 返回总存储
            case .free:
                return freeSize.int64Value // 返回可用存储
            case .used:
                let usedSize = totalSize.int64Value - freeSize.int64Value // 计算已用存储
                return usedSize
            }
        } catch {
            print("Error retrieving storage info: \(error)")
            return nil
        }
    }
    
    func formatBytes(_ bytes: Int64) -> String {
        let formatter = ByteCountFormatter()
        formatter.allowedUnits = [.useKB, .useMB, .useGB] // 选择合适的单位
        formatter.countStyle = .file
        return formatter.string(fromByteCount: bytes)
    }

    
    func calculateTotalAssetSize(fetchResult: PHFetchResult<PHAsset>) -> Int64 {
        var totalSize: Int64 = 0
        
        fetchResult.enumerateObjects { (asset, index, stop) in
            let resources = PHAssetResource.assetResources(for: asset)
            print("当前 asset: \(asset)")
            print("资源数量: \(resources.count)")
            
            for resource in resources {
                print("资源类型: \(resource.type)")
                if let fileSize = resource.value(forKey: "fileSize") as? Int64 {
                    print("文件大小: \(fileSize)")
                    totalSize += fileSize
                } else {
                    print("无法获取文件大小")
                }
            }
        }
        
        return totalSize
    }
    
    
}


