//
//  PresentAppearAnimatedTransitioning.swift
//  PaiAi
//
//  Created by ffib on 2018/12/16.
//  Copyright © 2018 yb. All rights reserved.
//

import UIKit

final class PresentAppearAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
    
    weak var delegate: PresentAnimatorDelegate?
    fileprivate var animator: PresentAnimatable
    
    init(animator: PresentAnimatable) {
        self.animator = animator
        super.init()
    }
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard let toVC = transitionContext.viewController(forKey: .to),
            let toView = toVC.view,
            let animationView = delegate?.animationView else { return }

        transitionContext.containerView.addSubview(toView)
        
        let duration = transitionDuration(using: transitionContext)
        
        animator.toViewPresentedAnimation(duration: duration, in: toView)
        animator.contentViewAppearAnimation(duration: duration, in: animationView)
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) {
            let isCancelled = transitionContext.transitionWasCancelled
            transitionContext.completeTransition(!isCancelled)
            UIApplication.shared.endIgnoringInteractionEvents()
        }
    }
}