//
//  PhotoManager.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/24.
//




import Photos
import UIKit

let PhotoManagerShared = PhotoManager.shared
class PhotoManager {
    static let shared = PhotoManager()

    /// 保存图片到相册
    /// - Parameters:
    ///   - image: 要保存的 UIImage
    ///   - completion: 保存结果的回调，返回成功与否和错误信息
    func saveToAlbum(_ data:Any, completion: @escaping (Bool, Error?) -> Void) {
        // 检查相册权限
        PHPhotoLibrary.requestAuthorization { status in
            DispatchQueue.main.async {
                switch status {
                case .authorized:
                    // 权限已授权，保存图片
                    self.save(data: data, completion: completion)
                case .limited:
                    // 在受限权限下保存图片
                    self.save(data: data, completion: completion)
                case .denied, .restricted:
                    // 权限被拒绝或受限
                    completion(false, NSError(domain: "PhotoSaver", code: 1, userInfo: [NSLocalizedDescriptionKey: "Photo Library access is denied."]))
                case .notDetermined:
                    // 不会进入这个分支，因为已经请求了权限
                    completion(false, NSError(domain: "PhotoSaver", code: 2, userInfo: [NSLocalizedDescriptionKey: "Photo Library access not determined."]))
                @unknown default:
                    completion(false, NSError(domain: "PhotoSaver", code: 3, userInfo: [NSLocalizedDescriptionKey: "Unknown authorization status."]))
                }
            }
        }
    }

    /// 保存视频到相册的具体实现
    private func save(data:Any, completion: @escaping (Bool, Error?) -> Void) {

        PHPhotoLibrary.shared().performChanges({
            
            
            if let url = data as? URL {
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
            }else if let image = data as? UIImage {
                PHAssetChangeRequest.creationRequestForAsset(from: image)
            }
        
    
        }) { success, error in
            DispatchQueue.main.async {
                completion(success, error)
                
//                if success {
//                    TSMineVM.kFirstSaveRateAction()
//                }
            }
        }
    }
    
}
extension PhotoManager {
    

}
