//
//  SlideInTransition.swift
//  SampleApp
//
//  Created by Apple on 12/09/19.
//  Copyright © 2019 None. All rights reserved.
//

import UIKit

class TransactionMenuTransitionManager: NSObject,UIViewControllerAnimatedTransitioning,UIViewControllerTransitioningDelegate {
    var isPresenting = false
    var delegate:MenuTransitionManagerDelegate?
    var dimmingView = UIView()
    @objc func dismissView() {
        self.delegate?.dismiss()
    }
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard  let toViewController = transitionContext.viewController(forKey: .to) else {return}
        guard let fromViewVontroller = transitionContext.viewController(forKey: .from) else {return}
        let containerController = transitionContext.containerView
        
        let finalWidth = toViewController.view.bounds.width*0.8
        let finalHeight = toViewController.view.bounds.height
        
        if isPresenting {
            dimmingView.backgroundColor = .black
            dimmingView.alpha = 0.0
            
            containerController.addSubview(dimmingView)
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissView))
            
            dimmingView.addGestureRecognizer(tapGesture)
            dimmingView.frame = containerController.bounds
            containerController.addSubview(toViewController.view)
            toViewController.view.frame = CGRect(x: -finalWidth, y: 0, width: finalWidth, height: finalHeight)
        }
        let transform = {
            self.dimmingView.alpha = 0.5
            toViewController.view.transform = CGAffineTransform(translationX: finalWidth, y: 0)
        }
        let idenity = {
            self.dimmingView.alpha = 0.0
            fromViewVontroller.view.transform = .identity
        }
        let duration = transitionDuration(using: transitionContext)
        let isCancelled = transitionContext.transitionWasCancelled
        
        UIView.animate(withDuration: duration, animations: {
            self.isPresenting ? transform() : idenity()
        }) { (_) in
            transitionContext.completeTransition((!isCancelled))
        }
    }
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresenting = false
        return self
    }
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresenting = true
        return self
    }
    
}
@objc protocol MenuTransitionManagerDelegate {
    func dismiss()
}
