
#import "RNLoading.h"
#import "MBProgressHUD.h"

@interface RNLoading()

@property (strong,nonatomic) MBProgressHUD *hud;

@end
@implementation RNLoading


RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(show)
{
    if (!self.hud) {
        self.hud  =  [[MBProgressHUD alloc]initWithView:[self.class topViewController].view];
        self.hud.bezelView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
        self.hud.contentColor = [UIColor whiteColor];
        
    }
    
    __weak __typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.hud.removeFromSuperViewOnHide = YES;
        [[self.class topViewController].view addSubview:self.hud];
        [weakSelf.hud showAnimated:YES];
    });
}

RCT_EXPORT_METHOD(hide)
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:[self.class topViewController].view animated:YES];
        // 当RN reset路由时，由于MBProgressHUD已经显示到界面上，但是HUD的父视图已经被销毁，故只能从视图树移除
        UIViewController *rootViewController = [[UIApplication sharedApplication].delegate window].rootViewController;
        if (rootViewController) {
            for (UIView *subView in rootViewController.view.subviews) {
                if([subView isKindOfClass:[MBProgressHUD class]]) {
                    [subView removeFromSuperview];
                }
            }
        }
    });
}

#pragma mark - Private
+ (UIViewController *)topViewController {
    return [self.class topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}

+ (UIViewController *)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabBarController = (UITabBarController *)rootViewController;
        return [self.class topViewControllerWithRootViewController:tabBarController.selectedViewController];
    }
    else if ([rootViewController isKindOfClass:[UITabBarController class]]){
        UITabBarController *tabBarController = (UITabBarController *)rootViewController;
        return [self.class topViewControllerWithRootViewController:tabBarController.selectedViewController];
    }
    else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self.class topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self.class topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}


@end
  
