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

import UIKit

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

extension NowPlayingSlideUpAnimator : 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 container = transitionContext.containerView
		container.insertSubview(toVC.view, aboveSubview: fromVC.view)
		
		
		let frame = fromVC.view.frame
		let finalHeight = frame.size.height - statusBarHeight()
		let size = CGSize(width: frame.size.width, height: finalHeight)
		
		let bottomGuideHeight = fromVC.bottomLayoutGuide.length
		let miniPlayerOffset = bottomGuideHeight + MiniPlayerViewController.expandedLayoutHeight
		
		let startTopLeftCorner = CGPoint(x: frame.origin.x , y: frame.size.height - miniPlayerOffset)
		let startFrame = CGRect(origin: startTopLeftCorner, size: size)
		toVC.view.frame = startFrame
		toVC.view.alpha = 0
		
		let endFrame = CGRect(origin: CGPoint(x: frame.origin.x, y: statusBarHeight()), size: size)
		
		UIView.animate(
			withDuration: fadeDuration,
			animations: {
				toVC.view.alpha = 1.0
		},
			completion: { _ in
				UIView.animate(
					withDuration: self.slideDuration,
					animations: {
						toVC.view.frame = endFrame
				},
					completion: { _ in
						transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
				})
		})
	}
}

extension NowPlayingSlideUpAnimator {
	private func statusBarHeight() -> CGFloat {
		return min(UIApplication.shared.statusBarFrame.width, UIApplication.shared.statusBarFrame.height)
	}
}

