//
//  SubNavSwipeAnimator.swift
//  MobileFirstFramework
//
//  Created by Matt Bruce on 10/22/21.
//  Copyright © 2021 Verizon Wireless. All rights reserved.
//

import Foundation
import MVMCore

@objcMembers public class SubNavSwipeAnimator: NSObject, MVMCoreViewControllerAnimatedTransitioning {
    @objc dynamic public var interactiveTransitionCanceled: Bool =  false
    
    private var animationTime: TimeInterval = 0.0
    private var direction: UISwipeGestureRecognizer.Direction
    private weak var controller: UIViewController?
    
    public init(swipingDirection direction: UISwipeGestureRecognizer.Direction, controller: UIViewController) {
        self.direction = direction
        self.controller = controller
        super.init()
    }
    
    public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        animationTime = 0.5
        return animationTime
    }
    
    public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        controller?.view.isUserInteractionEnabled = false
        let containerView = transitionContext.containerView
        
        guard let originalViewController = transitionContext.viewController(forKey: .from),
              let destinationViewController = transitionContext.viewController(forKey: .to) else { return }
        
        var destStartFrame = containerView.bounds
        destStartFrame.origin.x = direction == .right ? -destStartFrame.size.width : destStartFrame.size.width
        containerView.addSubview(destinationViewController.view)
        destinationViewController.view.frame = destStartFrame
        
        let destEndFrame = containerView.bounds
        var origEndFrame = containerView.bounds
        origEndFrame.origin.x = direction == .right ? origEndFrame.size.width : -origEndFrame.size.width
        
        UIView.animate(withDuration: animationTime, animations: {
            originalViewController.view.frame = origEndFrame
            destinationViewController.view.frame = destEndFrame
        }) { finished in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    }
    
    public func animationEnded(_ transitionCompleted: Bool) {
        if !transitionCompleted {
            interactiveTransitionCanceled = true
        }
        controller?.view.isUserInteractionEnabled = true
    }
}
