//
// © 2018-2020 Qualcomm Technologies, Inc. and/or its subsidiaries. All rights reserved.
//

import UIKit

class NowPlayingSlideDownAnimator: NSObject {
	private let fadeDuration = 0.2
	private let slideDuration = 0.35
}

extension NowPlayingSlideDownAnimator : UIViewControllerAnimatedTransitioning {
	func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
		return fadeDuration + slideDuration
	}
	
	func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
		guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
			let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else {
				return
		}
		
		let bottomGuideHeight = fromVC.bottomLayoutGuide.length
		let miniPlayerOffset = bottomGuideHeight + MiniPlayerViewController.expandedLayoutHeight
		
		let frame = toVC.view.frame
		let endTopLeftCorner = CGPoint(x: frame.origin.x , y: frame.size.height - miniPlayerOffset)
		let endFrame = CGRect(origin: endTopLeftCorner, size: frame.size)
		
		UIView.animate(
			withDuration: slideDuration,
			animations: {
				fromVC.view.frame = endFrame
		},
			completion: { _ in
				UIView.animate(
					withDuration: self.fadeDuration,
					animations: {
						fromVC.view.alpha = 0
				}, completion: { _ in
					transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
				})
			}
		)
	}
}

