//
//  SpeakEleBaseNavigationCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/3.
//

import UIKit

class SpeakEleBaseNavigationCtr: UINavigationController, UIGestureRecognizerDelegate, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.isNavigationBarHidden = true
        self.delegate = self;
        self.interactivePopGestureRecognizer?.delegate = self
    }

    override var childForStatusBarStyle: UIViewController? {
        return self.topViewController
    }
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        super.pushViewController(viewController, animated: animated)
        if viewControllers.count == 1 {
            viewController.hidesBottomBarWhenPushed = false
        }
    }
    
    override func popViewController(animated: Bool) -> UIViewController? {
        let ctr = super.popViewController(animated: animated)
        self.AnimationState = .none
        return ctr
    }
    
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool{
        if children.count == 1 {
            return false
        }else {
            return true
        }
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
    func navigationController(_ navigationController: UINavigationController,
                                  animationControllerFor operation: UINavigationController.Operation,
                                  from fromVC: UIViewController,
                                  to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        if toVC.navigationController?.AnimationState  == .present {
            if operation == .push {
                return SpeakCustomPushAnimator()
            }else{
                return SpeakCustomPopAnimator()
            }
        }
        return nil
    }
    
}



fileprivate var state = SpeakEasyAssociatedKeys.navigationAniKey.rawValue

extension UINavigationController {
    
    enum navigationState : Int {
    case none = 0
    case present = 1
    }
    
    var AnimationState:navigationState {
        set {
            objc_setAssociatedObject(self, &state, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            let animation = objc_getAssociatedObject(self, &state) as? navigationState ?? .none
            return animation
        }
    }
    
}
