//
//  TSCommonTool.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

import Kingfisher
import Foundation
import AVFoundation
class TSCommonTool {
//
//    static func downLoadImage(_ urlStr:String, completion: @escaping (_ image:UIImage) -> Void) {
//        ImageDownloader.default.downloadImage(with: URL(string: urlStr)!, options: nil) { receivedSize, totalSize in
//            debugPrint(receivedSize)
//        } completionHandler: {
//            result in
//            switch result {
//            case .success(let value):
//                completion(value.image)
//            case .failure(let error):
//                print(error)
//            }
//        }
//    }
//    
    
    /// 下载图片，优先从缓存中取，支持设置缓存策略
    /// - Parameters:
    ///   - url: 图片的 URL 地址
    ///   - completion: 完成回调，返回图片或错误
    static func fetchImageWithCache(
        from urlString: String,
        completion: @escaping (UIImage?, Error?) -> Void
    ) {
        
        guard let url = URL(string: urlString) else{
            completion(nil, NSError(domain: "url null", code: 0))
            return
        }

        // 配置 Kingfisher 的缓存策略
        let options: KingfisherOptionsInfo = [
            .cacheOriginalImage,
            .memoryCacheExpiration(.days(7)),  // 内存缓存时间
            .diskCacheExpiration(.days(30)),  // 磁盘缓存时间
            .cacheSerializer(DefaultCacheSerializer.default)
        ]
        
        // 使用 Kingfisher 检查缓存是否存在
        let cache = ImageCache.default
        let cacheKey = url.absoluteString
        
        cache.retrieveImage(forKey: cacheKey, options: nil) { result in
            switch result {
            case .success(let value):
                if let image = value.image {
                    // 从缓存中取到图片
                    completion(image, nil)
                } else {
                    // 缓存中不存在图片，进行下载
                    downloadImage(from: url, options: options, completion: completion)
                }
            case .failure(let error):
                // 缓存检查失败，直接下载
                print("缓存检查失败: \(error.localizedDescription)")
                downloadImage(from: url, options: options, completion: completion)
            }
        }
    }
    
    
    /// 获取已缓存的磁盘图片文件路径
    /// - Parameters:
    ///   - urlString: 图片的 URL 地址
    ///   - completion: 完成回调，返回图片的磁盘路径或错误
    static func fetchImagePathWithCache(
        from urlString: String,
        completion: @escaping (String?, Error?) -> Void
    ) {
        guard let url = URL(string: urlString) else {
            completion(nil, NSError(domain: "InvalidURL", code: 0, userInfo: [NSLocalizedDescriptionKey: "无效的 URL"]))
            return
        }
        
        let cache = ImageCache.default
        let cacheKey = url.absoluteString
        if cache.isCached(forKey: cacheKey) {
            completion(cache.cachePath(forKey: cacheKey), nil)
        }else {
          completion(nil, NSError(domain: "CachePathError", code: 1, userInfo: [NSLocalizedDescriptionKey: "无法获取缓存路径"]))
        }

    }
    

    /// 下载图片并缓存
    /// - Parameters:
    ///   - url: 图片的 URL 地址
    ///   - options: Kingfisher 下载和缓存的选项
    ///   - completion: 完成回调，返回图片或错误
    static func downloadImage(
        from url: URL,
        options: KingfisherOptionsInfo,
        completion: @escaping (UIImage?, Error?) -> Void
    ) {
        KingfisherManager.shared.retrieveImage(with: url, options: options,progressBlock: { receivedSize, totalSize in
            debugPrint(receivedSize)
        }) { result in
            switch result {
            case .success(let value):
                completion(value.image, nil)
            case .failure(let error):
                completion(nil, error)
            }
        }
    }
    
    
    
    /// 下载并缓存文件，依据 URL 的后缀名动态设置文件名
    /// - Parameters:
    ///   - url: 文件的 URL 地址
    ///   - completion: 完成回调，返回本地缓存路径或错误
    static func downloadAndCacheFile(from urlString: String, fileEx:String? = nil, cacheDirectory:String = "cacheVideo",completion: @escaping (String?, Error?) -> Void) {
        
        guard let url = URL(string: urlString) else{
            completion(nil, NSError(domain: "url null", code: 0))
            return
        }
        
        
        if !urlString.contains("http") && urlString.contains("/"){
            completion(urlString.fillCachePath, nil)
            return
        }
        
        let fileManager = FileManager.default
        
        // 获取缓存目录下的 `cacheVideo` 文件夹路径
        let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
        let cacheVideoDirectory = cacheDirectory.appendingPathComponent("cacheVideo")
        
        // 创建 `cacheVideo` 文件夹（如果不存在）
        if !fileManager.fileExists(atPath: cacheVideoDirectory.path) {
            do {
                try fileManager.createDirectory(at: cacheVideoDirectory, withIntermediateDirectories: true, attributes: nil)
            } catch {
                completion(nil, error)
                return
            }
        }
        
        // 使用 URL 的 MD5 哈希值作为缓存文件名，附加 URL 的后缀名
        var fileExtension = fileEx
        fileExtension = fileExtension ?? (url.pathExtension.isEmpty ? "tmp" : url.pathExtension)
        
        
        let fileName = url.path.md5 + ".\(fileExtension!)"
        let cachedFileURL = cacheVideoDirectory.appendingPathComponent(fileName)
        
        // 检查文件是否已存在于缓存中
        if fileManager.fileExists(atPath: cachedFileURL.path) {
            print("文件已存在于缓存中: \(cachedFileURL)")
            completion(cachedFileURL.path, nil)
            return
        }
        
        // 下载文件
        let task = URLSession.shared.downloadTask(with: url) { tempFileURL, response, error in
            if let error = error {
                completion(nil, error)
                return
            }
            
            guard let tempFileURL = tempFileURL else {
                completion(nil, NSError(domain: "DownloadError", code: -1, userInfo: [NSLocalizedDescriptionKey: "临时文件路径不存在"]))
                return
            }
            
            do {
                try fileManager.moveItem(at: tempFileURL, to: cachedFileURL)
                print("文件下载并缓存成功: \(cachedFileURL)")
                completion(cachedFileURL.path, nil)
            } catch {
                completion(nil, error)
            }
        }
        
        task.resume()
    }

}



/// 主线程延迟执行回调
/// - Parameters:
///   - delay: 延迟时间（秒）
///   - completion: 延迟后的回调
func kDelayOnMainThread(_ delay: TimeInterval, completion: @escaping () -> Void) {
    DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
        completion()
    }
}

func kDelayMainShort(completion: @escaping () -> Void) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        completion()
    }
}

/// 在主线程上执行代码
/// - Parameter block: 要执行的代码块
func kExecuteOnMainThread(_ block: @escaping () -> Void) {
    if Thread.isMainThread {
        block()
    } else {
        DispatchQueue.main.async {
            block()
        }
    }
}

