//
//  NavigationControllerProxy.swift
//  PaiaiUIKit
//
//  Created by FFIB on 2019/1/16.
//  Copyright © 2019 FFIB. All rights reserved.
//

import UIKit

class NavigationControllerProxy: NSObject, UINavigationControllerDelegate {
    weak var delegate: NavigationControllerDelegate?

    init(target: NavigationControllerDelegate) {
        delegate = target
    }

    func navigationController(_ navigationController: UINavigationController,
                              willShow viewController: UIViewController, animated: Bool) {
        delegate?.navigationController(navigationController, willShow: viewController, animated: true)
    }

    func navigationController(_ navigationController: UINavigationController,
                              didShow viewController: UIViewController, animated: Bool) {
        delegate?.navigationController(navigationController, didShow: viewController, animated: true)
    }

    func navigationController(_ navigationController: UINavigationController,
                              animationControllerFor operation: UINavigationController.Operation,
                              from fromVC: UIViewController,
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return delegate?.navigationController(navigationController,
                                              animationControllerFor: operation,
                                              from: fromVC, to: toVC)
    }
}

extension UINavigationController {
    private struct AssociatedKeys {
        static var proxyKey = "NavigationControllerProxyKey"
    }

    private var proxy: NavigationControllerProxy? {
        get { return objc_getAssociatedObject(self, &AssociatedKeys.proxyKey) as? NavigationControllerProxy }
        set { objc_setAssociatedObject(self,
                                       &AssociatedKeys.proxyKey,
                                       newValue,
                                       objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
    }

    func setDelegate<T: NavigationControllerDelegate>(_ target: T) {
        proxy = NavigationControllerProxy(target: target)
        delegate = proxy
    }
}