//
//  UIImageView+Extension.swift
//  MyTatvaCare
//
//  Created by Nirav Ramani on 07/05/25.
//

import Foundation
import UIKit
import ImageIO

extension UIImageView {
    func loadGif(named name: String) {
        DispatchQueue.global().async {
            guard let path = Bundle(for: ImageTVC.self).path(forResource: name, ofType: "gif"),
                  let data = NSData(contentsOfFile: path) else {
                print("GIF not found: \(name)")
                return
            }

            guard let source = CGImageSourceCreateWithData(data, nil) else { return }

            var images = [UIImage]()
            var totalDuration: Double = 0

            let count = CGImageSourceGetCount(source)

            for i in 0..<count {
                if let cgImage = CGImageSourceCreateImageAtIndex(source, i, nil) {
                    let duration = UIImageView.frameDuration(at: i, source: source)
                    totalDuration += duration
                    let image = UIImage(cgImage: cgImage)
                    images.append(image)
                }
            }

            DispatchQueue.main.async {
                self.animationImages = images
                self.animationDuration = totalDuration
                self.animationRepeatCount = 0
                self.startAnimating()
            }
        }
    }

    // Helper to get frame duration from GIF metadata
    private static func frameDuration(at index: Int, source: CGImageSource) -> Double {
        var duration = 0.1
        let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as Dictionary?
        if let gifProperties = properties?[kCGImagePropertyGIFDictionary as String as NSObject] as? [String: Any] {
            if let delayTime = gifProperties[kCGImagePropertyGIFUnclampedDelayTime as String] as? Double {
                duration = delayTime
            } else if let delayTime = gifProperties[kCGImagePropertyGIFDelayTime as String] as? Double {
                duration = delayTime
            }
        }
        return duration < 0.011 ? 0.1 : duration
    }
}
