#import "SplashScreen.h"
#import <React/RCTBridge.h>
#import <React/RCTUtils.h>

@implementation SplashScreen {
    BOOL _isPreserved;
    UIView* _splashView;
}

RCT_EXPORT_MODULE()

- (instancetype)init {
    if (self = [super init]) {
        _isPreserved = NO;
        [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onWindowDidBecomeVisible:)
                                                 name:UIWindowDidBecomeVisibleNotification
                                               object:nil];
    }
    return self;
}

+ (BOOL)requiresMainQueueSetup {
    return YES;
}

RCT_EXPORT_METHOD(preserve) {
    dispatch_async(dispatch_get_main_queue(), ^{
        self->_isPreserved = YES;
        UIViewController *rootViewController = [self getRootViewController];
        if (rootViewController != nil) {
            self->_splashView = [self getSplashView];
            if (self->_splashView != nil) {
                [rootViewController.view addSubview:self->_splashView];
            }
        }
    });
}

RCT_EXPORT_METHOD(hide) {
    dispatch_async(dispatch_get_main_queue(), ^{
        self->_isPreserved = NO;
        if (self->_splashView != nil) {
            [UIView animateWithDuration:0.25 animations:^{
                self->_splashView.alpha = 0;
            } completion:^(BOOL finished) {
                [self->_splashView removeFromSuperview];
                self->_splashView = nil;
            }];
        }
    });
}

RCT_EXPORT_METHOD(show) {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController *rootViewController = [self getRootViewController];
        if (rootViewController != nil) {
            self->_splashView = [self getSplashView];
            if (self->_splashView != nil) {
                self->_splashView.alpha = 0;
                [rootViewController.view addSubview:self->_splashView];
                [UIView animateWithDuration:0.25 animations:^{
                    self->_splashView.alpha = 1;
                }];
            }
        }
    });
}

- (UIViewController*)getRootViewController {
    UIWindow *window = RCTSharedApplication().delegate.window;
    return window.rootViewController;
}

- (UIView*)getSplashView {
    NSString *launchScreenName = @"LaunchScreen";
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:launchScreenName bundle:nil];
    UIViewController *launchViewController = [storyboard instantiateInitialViewController];
    if (launchViewController != nil) {
        UIView *view = launchViewController.view;
        view.frame = [UIScreen mainScreen].bounds;
        return view;
    }
    return nil;
}

- (void)onWindowDidBecomeVisible:(NSNotification*)notification {
    if (!_isPreserved && _splashView != nil) {
        [self hide];
    }
}

@end
