//
//  UIImageView+Extension.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/8/20.
//

import UIKit

extension UIImageView {
    
    func loadGif(name: String ,oftype:String = "gif" ,repeatCount:Int = 0) {
        guard let path = Bundle.main.path(forResource: name, ofType: oftype) else { return }
        let url = URL(fileURLWithPath: path)
        DispatchQueue.global().async {
            guard let data = try? Data(contentsOf: url),
                  let source = CGImageSourceCreateWithData(data as CFData, nil) else { return }
            var images:[UIImage] = []
            let frameCount = CGImageSourceGetCount(source)
            for i in 0..<frameCount {
                if let cgImage = CGImageSourceCreateImageAtIndex(source, i, nil) {
                    images.append(UIImage(cgImage: cgImage))
                }
            }
            DispatchQueue.main.async {
                self.animationRepeatCount = repeatCount
                self.animationImages = images
                self.animationDuration = Double(frameCount) * 0.02
                self.startAnimating()
                if repeatCount == 1 {
                    DispatchQueue.main.asyncAfter(deadline: .now() + (Double(frameCount) * 0.02 - 0.01)) {
                        self.image = images.last
                        self.stopAnimating()
                    }
                }
            }
        }
    }
    
}
