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

import UIKit

class GestureRecognizerProxy: NSObject, UIGestureRecognizerDelegate {
    weak var delegate: GestureRecognizerDelegate?

    init(target: GestureRecognizerDelegate) {
        delegate = target
    }

    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return delegate?.gestureRecognizerShouldBegin(gestureRecognizer) ?? false
    }

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        return delegate?.gestureRecognizer(gestureRecognizer, shouldReceive: touch) ?? false
    }

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
                           shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return delegate?.gestureRecognizer(gestureRecognizer, shouldRecognizeSimultaneouslyWith: otherGestureRecognizer) ?? false //swiftlint:disable:this line_length
    }
}

extension UIGestureRecognizer {
    private struct AssociatedKeys {
        static var proxyKey = "GestureRecognizerProxyKey"
    }

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

    func setDelegate(_ target: GestureRecognizerDelegate) {
        proxy = GestureRecognizerProxy(target: target)
        delegate = proxy
    }
}