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

import UIKit

final class PresentDisappearAnimatedTransitioning: 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 fromVC = transitionContext.viewController(forKey: .from),
            let fromView = fromVC.view,
            let toVC = transitionContext.viewController(forKey: .to),
            let toView = toVC.view,
            let animationView = delegate?.animationView else { return }

        let duration = transitionDuration(using: transitionContext)
        
        animator.fromViewPresentingAnimation(duration: duration, in: fromView)
        animator.contentViewDisappearAnimation(duration: duration, in: animationView)
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) {
            let isCancelled = transitionContext.transitionWasCancelled
            transitionContext.completeTransition(!isCancelled)
            transitionContext.containerView.addSubview(toView)
            fromView.removeFromSuperview()
        }
    }
}