//
//  UIImageView+Ex.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//
import Kingfisher


class TSCustomActivityIndicator: Indicator {
    let activityIndicator = UIActivityIndicatorView(style: .medium)
    
    init(color: UIColor) {
        activityIndicator.color = color
    }
    
    func startAnimatingView() {
        activityIndicator.startAnimating()
    }
    
    func stopAnimatingView() {
        activityIndicator.stopAnimating()
    }
    
    var view: IndicatorView {
        return activityIndicator
    }
}

public extension UIImageView {

    /// 创建并配置 UIImageView
    /// - Parameters:
    ///   - imageName: 图片名称
    ///   - contentMode: 内容模式，默认为 `.scaleAspectFit`
    ///   - backgroundColor: 背景颜色，默认为透明
    /// - Returns: 配置完成的 UIImageView 实例
    static public func createImageView(
                                image:UIImage? = nil,
                                imageName: String? = nil,
                                contentMode: UIView.ContentMode = .scaleAspectFit,
                                backgroundColor: UIColor = .clear,
                                corner: CGFloat = 0.0,
                                autoMirrored: Bool = true
    ) -> UIImageView {
        let imageView = UIImageView()
                                    
        if let image = image{
            imageView.image = image
        }

        if let imageName = imageName ,imageName.count > 0 {
            if autoMirrored {
                imageView.image = UIImage(named: imageName)
            }else{
                imageView.image = UIImage(named: imageName)
            }
        }
        
        if let image = imageView.image,autoMirrored{
            imageView.image = image.mirrored
        }
        
        imageView.contentMode = contentMode
        imageView.backgroundColor = backgroundColor
        imageView.cornerRadius = corner
        return imageView
    }
    
    /// 异步创建并加载图片的 UIImageView
    /// - Parameters:
    ///   - imageName: 本地占位图片名称
    ///   - urlString: 图片的 URL 字符串
    ///   - contentMode: 内容模式，默认为 `.scaleAspectFit`
    ///   - backgroundColor: 背景颜色，默认为透明
    ///   - showLoading: 是否显示加载动画，默认为 `true`
    ///   - completion: 图片加载成功后的回调
    static public func createAsyncImageView(urlString: String?,
                                     placeholder:UIImage?,
                                     contentMode: UIView.ContentMode = .scaleAspectFit,
                                        adaptiveMode:Bool = false,
                                     backgroundColor: UIColor = .clear,
                                     showLoading: Bool = false,
                                    progressBlock: ((Float)->Void)? = nil,
                                     completion: ((UIImage?) -> Void)? = nil) -> UIImageView {
        let imageView = UIImageView()
        imageView.setAsyncImage(urlString: urlString,
                                placeholder:placeholder,
                                contentMode:contentMode,
                                adaptiveMode:adaptiveMode,
                                backgroundColor:backgroundColor,
                                showLoading:showLoading,
                                progressBlock:progressBlock,
                                completion:completion)
        return imageView
    }

    
    
    public func setAsyncImage(urlString: String?,
                     placeholder: UIImage? = nil,
                     contentMode: UIView.ContentMode? = nil,
                 adaptiveMode:Bool = false,
                 backgroundColor: UIColor? = nil,
                      showLoading: Bool = false,
                        progressBlock: ((Float)->Void)? = nil,
                      completion: ((UIImage?) -> Void)? = nil){
        let imageView = self
        
        if let contentMode = contentMode {
            imageView.contentMode = contentMode
        }
        
        if let backgroundColor = backgroundColor {
            imageView.backgroundColor = backgroundColor
        }
 
        imageView.image = placeholder
        
        guard let urlString = urlString else {
            completion?(nil)
            return
        }
      
        if urlString.count == 0 {
            completion?(nil)
            return
        }
        
        if urlString.contains("http") {
            guard let url = URL(string: urlString) else {
                completion?(nil)
                return
            }
            kf.indicatorType = showLoading ? .custom(indicator: TSCustomActivityIndicator(color: .white)) : .none
            imageView.kf.setImage(with: url,
                 placeholder: placeholder,
                     options: nil,
                progressBlock: { receivedSize, totalSize in
                let progress = receivedSize/totalSize
                progressBlock?(Float(progress))
            }){ result in
                
                if let image = try? result.get().image {
                    kMainShort {
                        completion?(image)
                    }
                }else{
                    completion?(nil)
                }
            }
            
        }else if urlString.contains("/") {
            imageView.image = UIImage(contentsOfFile: urlString)
            completion?(imageView.image)
        }else {
            if let image = UIImage(named: urlString) {
                imageView.image = image
                completion?(image)
            }
        }
    }

}

public extension UIImageView {
    
    static public func createRightArrow() -> UIImageView {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "right_arrow")?.mirrored
        return imageView
    }
    
    /// 根据图片比例自动选择最佳缩放模式
    public func adaptiveScale() {
//        guard let image = image else { return }
//        
//        let viewSize = bounds.size
//        let imageRatio = image.size.width / image.size.height
//        let viewRatio = viewSize.width / viewSize.height
//        
//        let contentNewMode:UIView.ContentMode = imageRatio > viewRatio ? .scaleAspectFill : .scaleAspectFit
//        self.contentMode = contentNewMode
//        
//        dePrint("UIImageView.adaptiveScale contentMode =\(contentNewMode)")
    }
}

public extension UIImageView {
    public func setImage(_ image: UIImage?, duration: CFTimeInterval = 0.2, animated: Bool = true) {
        if let image = image {
            if animated {
                UIView.transition(
                    with: self,
                    duration: duration,
                    options: [.transitionCrossDissolve, .curveEaseInOut, .allowUserInteraction]
                ) {
                    self.image = image
                }
            }else {
                self.image = image
            }
        }
    }
}
