//
//  BaseRNViewController.m
//  testnpm
//
//  Created by Castiel on 2018/4/3.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "BaseRNViewController.h"
#import <React/RCTRootView.h>
#import "DGActivityIndicatorView.h"

@implementation BaseRNViewController {
    RCTBridge *_bridge;
    NSString *_moduleName;
    NSURL *_bundlePath;
    RCTRootView *_rctRootView;
    DGActivityIndicatorView *_activityIndicatorView;
}

- (instancetype)initWithBundlePath:(NSURL *) bundlePath withModuleName:(NSString *) moduleName initialProperties:(NSDictionary *)initialProperties
{
    self = [super init];
    if (self) {
        _moduleName = moduleName;
        _bundlePath = bundlePath;
        _bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:nil];
        
        _rctRootView = [[RCTRootView alloc] initWithBridge:_bridge moduleName:moduleName initialProperties:initialProperties];
        [self setView:_rctRootView];
        [self showLoadingDialog];
    }
    return self;
}

- (void) reloadWithBundlePath:(NSURL *) bundlePath initialProperties:(NSDictionary *)initialProperties
{
    _bundlePath = bundlePath;
    [_bridge reload];
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge {
    return _bundlePath;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void) showLoadingDialog {
    _activityIndicatorView = [[DGActivityIndicatorView alloc] initWithType:DGActivityIndicatorAnimationTypeLineScale tintColor:[UIColor grayColor]];
    [_activityIndicatorView setBackgroundColor:[UIColor colorWithWhite:255 alpha:1.0]];
    _activityIndicatorView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    [self.view addSubview:_activityIndicatorView];
    [_activityIndicatorView startAnimating];
    
    UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [_activityIndicatorView addGestureRecognizer:tapGesturRecognizer];
}

-(void)tapAction:(id)tap {
    [self hideLoadingDialog];
}

- (void) hideLoadingDialog {
    if (_activityIndicatorView != nil) {
        [_activityIndicatorView stopAnimating];
        [_activityIndicatorView removeFromSuperview];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
