//
//  TSImageStoreTool.swift
//  Pods
//
//  Created by 100Years on 2025/6/16.
//
import Kingfisher


public class TSImageStoreTool  {

    public static func retrieveImageInMemoryCache(urlString: String) -> UIImage? {
        return ImageCache.default.retrieveImageInMemoryCache(forKey: urlString)
    }

    public static func storeImage(image:UIImage,urlString: String){
        if let url = URL(string: urlString){
            ImageCache.default.store(image, forKey: url.cacheKey)
        }
    }

    
    public static func removeImage(urlString: String){
        if urlString.isEmpty {
            return
        }
        
        if let url = URL(string: urlString){
            ImageCache.default.removeImage(forKey: url.cacheKey)
        }
    }
    
    public static func downloadImageWithProgress(
        urlString: String,
        progressHandler: ((Float) -> Void)? = nil,
        completion: @escaping (UIImage?) -> Void
    ) {
//        // 处理非HTTP URL的情况
//        if !urlString.contains("http") {
//            handleLocalImage(urlString: urlString, completion: completion)
//            return
//        }
        
        guard let url = URL(string: urlString) else {
            completion(nil)
            return
        }
        
        let cacheKey = url.cacheKey
        
        // 1. 首先尝试从内存缓存获取
        if let memoryImage = ImageCache.default.retrieveImageInMemoryCache(forKey: cacheKey) {
            completion(memoryImage)
            return
        }
        
        // 2. 然后尝试从磁盘缓存获取
        ImageCache.default.retrieveImage(forKey: cacheKey) { result in
            switch result {
            case .success(let value):
                if let diskImage = value.image {
                    // 将从磁盘获取的图片存入内存缓存
                    ImageCache.default.store(diskImage, forKey: cacheKey, toDisk: false)
                    DispatchQueue.main.async {
                        completion(diskImage)
                    }
                    return
                }
                
                // 3. 如果缓存中没有，则从网络下载
                downloadFromNetwork(url: url, cacheKey: cacheKey, progressHandler: progressHandler, completion: completion)
                
            case .failure:
                // 如果磁盘缓存获取失败，也尝试从网络下载
                downloadFromNetwork(url: url, cacheKey: cacheKey, progressHandler: progressHandler, completion: completion)
            }
        }
    }

//    private static func handleLocalImage(urlString: String, completion: @escaping (UIImage?) -> Void) {
//        if urlString.contains("/") {
//            completion(UIImage(contentsOfFile: urlString.fillCachePath))
//        } else {
//            completion(UIImage(named: urlString))
//        }
//    }

    private static func downloadFromNetwork(
        url: URL,
        cacheKey: String,
        progressHandler: ((Float) -> Void)?,
        completion: @escaping (UIImage?) -> Void
    ) {
        KingfisherManager.shared.retrieveImage(
            with: url,
            options: [],
            progressBlock: { receivedSize, totalSize in
                let progress = Float(receivedSize) / Float(totalSize)
                DispatchQueue.main.async {
                    progressHandler?(progress)
                }
            },
            completionHandler: { result in
                DispatchQueue.main.async {
                    switch result {
                    case .success(let value):
                        // 将下载的图片存入缓存
                        ImageCache.default.store(value.image, forKey: cacheKey)
                        completion(value.image)
                    case .failure:
                        completion(nil)
                    }
                }
            }
        )
    }
    
}
