//
//  KBURLOpenBridge.m
//

#import "KBURLOpenBridge.h"
#import <objc/message.h>

@implementation KBURLOpenBridge

+ (BOOL)openURLViaResponder:(NSURL *)url from:(UIResponder *)start {
#if KB_URL_BRIDGE_ENABLE
    if (!url || !start) return NO;
    SEL sel = NSSelectorFromString(@"openURL:");
    UIResponder *responder = start;
    while (responder) {
        @try {
            if ([responder respondsToSelector:sel]) {
                // 尽量按签名调用；若失败则回退 performSelector
                BOOL handled = NO;
                // 尝试 (BOOL)openURL:(NSURL *)
                BOOL (*funcBool)(id, SEL, NSURL *) = (BOOL (*)(id, SEL, NSURL *))objc_msgSend;
                if (funcBool) {
                    handled = funcBool(responder, sel, url);
                } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
                    [responder performSelector:sel withObject:url];
                    handled = YES;
#pragma clang diagnostic pop
                }
                return handled;
            }
        } @catch (__unused NSException *e) {
            // ignore and continue
        }
        responder = responder.nextResponder;
    }
    return NO;
#else
    (void)url; (void)start;
    return NO;
#endif
}

@end

