//
//  UIView+Extension.m
//  SLAiELTS
//
//  Created by Gusont on 2023/3/1.
//

#import "UIView+Extension.h"
#import <objc/runtime.h>

static char kActionHandlerTapGestureKey;
static char kActionHandlerTapBlockKey;

@implementation UIView (Extension)

- (UIViewController *)viewController
{
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

- (void)viewTapExtension:(UITapGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateRecognized) {
        void(^action)(void) = objc_getAssociatedObject(self, &kActionHandlerTapBlockKey);
        if (action) {
            action();
        }
    }
}

- (void)addTapWithBlock:(void(^)(void))block {
    UITapGestureRecognizer *tap = objc_getAssociatedObject(self, &kActionHandlerTapGestureKey);
    if (!tap) {
        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapExtension:)];
        self.userInteractionEnabled = YES;
        [self addGestureRecognizer:tap];
        objc_setAssociatedObject(self, &kActionHandlerTapGestureKey, tap, OBJC_ASSOCIATION_RETAIN);
    }
    objc_setAssociatedObject(self, &kActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
}

@end
