import React
import UIKit
import Lottie

private var waiting = true
private var loadingView: UIView? = nil
private var animationView: LottieAnimationView?

@objc(ReadyWalletSplash)
class ReadyWalletSplash: NSObject {
    @objc class func showSplash(inRootView rootView: UIView) {
        if loadingView == nil {
            let storyboard = UIStoryboard(name: "ReadySplash", bundle: nil)
            loadingView = (storyboard.instantiateInitialViewController()?.view)!
            
            animationView = .init(name: "ReadyWalletSplash")
            
            animationView!.contentMode = .scaleAspectFit
            // Calculate the scaled size
            let scale = min(loadingView!.bounds.size.width / 720,
                             loadingView!.bounds.size.height / 1192)
            let width = 720 * scale
            let height = 1192 * scale
            animationView?.frame = CGRect(x: (loadingView!.bounds.size.width - width ) / 2,
                                     y: loadingView!.bounds.size.height - height,
                                     width: width,
                                     height: height)
            animationView!.loopMode = .playOnce
            animationView!.animationSpeed = 0.4
            loadingView?.addSubview(animationView!)
        }
        waiting = false
        loadingView?.frame = rootView.bounds
        animationView!.play()
        rootView.addSubview(loadingView!)
    }

    @objc class func hide() {
        if waiting {
            DispatchQueue.main.async {
                waiting = false
            }
        } else {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                loadingView?.removeFromSuperview()
            }
        }
    }


    @objc(hide)
    func hide() {
        ReadyWalletSplash.hide()
    }
}

