//
//  UIViewController+RangersAppLog.m
//  react-native-rangers-applog-reactnative-plugin
//
//  Created by bytedance on 2022/6/27.
//

#if __has_include(<React/RCTLog.h>)
#import <React/RCTLog.h>
#else
#import "RCTLog.h"
#endif

#if __has_include(<React/RCTRootView.h>)
#import <React/RCTRootView.h>
#else
#import "RCTRootView.h"
#endif

#import "RangersAppLogSwizzle.h"
#import "RangersAppLogNavStack.h"
#import "UIViewController+RangersAppLog.h"

@implementation UIViewController (RangersAppLog)

+ (void)load {
    static dispatch_once_t onceToken_rn_bd;
    static IMP original_DidAppear_Imp_rn_bd = nil;
    static IMP original_DidDisappear_Imp_rn_bd = nil;
  
    dispatch_once(&onceToken_rn_bd, ^{
        original_DidAppear_Imp_rn_bd = bd_swizzle_instance_methodWithBlock_rn([self class], @selector(viewDidAppear:), ^(UIViewController *_self, BOOL animated){
            if (original_DidAppear_Imp_rn_bd) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    @try {
                        [[RangersAppLogNavStack shared] appear:_self];
                    } @catch (NSException *exception) {
                        RCTLogInfo(@"viewDidAppear error: %@", exception);
//                        NSLog(@">>> %@", exception);
                    }
                });
                ((void ( *)(id, SEL, BOOL))original_DidAppear_Imp_rn_bd)(_self, @selector(viewDidAppear:), animated);
            }
        });
        
        original_DidDisappear_Imp_rn_bd = bd_swizzle_instance_methodWithBlock_rn([self class], @selector(viewDidDisappear:), ^(UIViewController *_self, BOOL animated){
            if (original_DidDisappear_Imp_rn_bd) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    @try {
                        [[RangersAppLogNavStack shared] disappear:_self];
                    } @catch (NSException *exception) {
                        RCTLogInfo(@"viewDidDisappear error: %@", exception);
                    }
                });

                ((void ( *)(id, SEL, BOOL))original_DidDisappear_Imp_rn_bd)(_self, @selector(viewDidDisappear:), animated);
            }
        });

    });
}


@end
