//
//  ViewControllerTransitioningProxy.swift
//  PaiaiUIKit
//
//  Created by FFIB on 2019/1/28.
//  Copyright © 2019 FFIB. All rights reserved.
//

import UIKit

class ViewControllerTransitioningProxy: NSObject, UIViewControllerTransitioningDelegate {
    weak var delegate: ViewControllerTransitioningDelegate?
    
    init(target: ViewControllerTransitioningDelegate) {
        delegate = target
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return delegate?.animationController(forDismissed: dismissed)
    }
    
    func animationController(forPresented presented: UIViewController,
                             presenting: UIViewController,
                             source: UIViewController)
        -> UIViewControllerAnimatedTransitioning? {
            return delegate?.animationController(forPresented: presented,
                                                 presenting: presenting,
                                                 source: source)
    }
}

extension UIViewController {
    private struct AssociatedKeys {
        static var proxyKey = "ViewControllerTransitioningProxyKey"
    }
    
    private var proxy: ViewControllerTransitioningProxy? {
        get { return objc_getAssociatedObject(self, &AssociatedKeys.proxyKey) as? ViewControllerTransitioningProxy }
        set { objc_setAssociatedObject(self, &AssociatedKeys.proxyKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
    }
    
    func setTransitioningDelegate<T: ViewControllerTransitioningDelegate>(_ target: T) {
        proxy = ViewControllerTransitioningProxy(target: target)
        transitioningDelegate = proxy
    }
}