//
//  MFTransparentGifView.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 3/19/19.
//  Copyright © 2019 Verizon Wireless. All rights reserved.
//

import UIKit

enum MFTransparentGIFViewError: Error {
    case gifNotFoundError
}

@objcMembers public class MFTransparentGIFView: FLAnimatedImageView {
    var imageData: Data?

    /** Creates the GIF display view with the passed in frame.
     frame: frame to set the view to.
     ImageName: name of the .gif to load. Should not contain the extension. Local images only.
     StartImmediately: should the gif immeidately begin playing. If YES, it will start. If NO, call [performAnimations] to start it.
     Duration: how long the animation takes to loop. Pass a negative value to use the default.
     LoopCompletionBlock: a block called whenever the gif finishes a loop.
     animatedImage : set as nil when use this view in reusable cell
     */
    public init(withFrame frame: CGRect, imageName: String, startImmediately: Bool, duration: TimeInterval, loopCompletionBlock: ((UInt) -> Void)?) throws {
        super.init(frame: frame)
        try loadImage(imageName, startImmediately: startImmediately, duration: duration, loopCompletionBlock: loopCompletionBlock)
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public func loadImage(_ imageName: String, startImmediately: Bool, duration: TimeInterval, loopCompletionBlock: ((UInt) -> Void)?) throws {
        contentMode = UIView.ContentMode.scaleAspectFill
        clipsToBounds = true
        
        if duration >= 0 {
            animationDuration = duration
        }
        self.loopCompletionBlock = loopCompletionBlock
        backgroundColor = .clear
        
        guard let url = MVMCoreUIUtility.bundleForMVMCoreUI()?.url(forResource: imageName, withExtension: "gif") else {
            throw MFTransparentGIFViewError.gifNotFoundError
        }
        imageData = try Data(contentsOf: url)
        
        runLoopMode = RunLoop.Mode.common.rawValue
        if startImmediately {
            performAnimations()
        }
    }
    
    public func loadGifWithData(_ imageData: Data) {
        contentMode = UIView.ContentMode.scaleAspectFill
        clipsToBounds = true
        backgroundColor = .clear
        self.imageData = imageData
        runLoopMode = RunLoop.Mode.common.rawValue
        performAnimations()
    }
    
    public func performAnimations() {
        animatedImage = FLAnimatedImage(animatedGIFData: imageData, optimalFrameCacheSize: 250, predrawingEnabled: true)
    }
}
