package com.reactnativenavigation.react;

import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.ReactContext;
import com.reactnativenavigation.NavigationActivity;

public class NavigationReactInitializer implements ReactInstanceManager.ReactInstanceEventListener {

	private final ReactInstanceManager reactInstanceManager;
	private final DevPermissionRequest devPermissionRequest;
	private boolean waitingForAppLaunchEvent = true;

	public NavigationReactInitializer(ReactInstanceManager reactInstanceManager, boolean isDebug) {
		this.reactInstanceManager = reactInstanceManager;
		this.devPermissionRequest = new DevPermissionRequest(isDebug);
	}

	public void onActivityCreated(final NavigationActivity activity) {
		reactInstanceManager.addReactInstanceEventListener(this);
		waitingForAppLaunchEvent = true;
	}

	public void onActivityResumed(NavigationActivity activity) {
		if (devPermissionRequest.shouldAskPermission(activity)) {
			devPermissionRequest.askPermission(activity);
		} else {
			reactInstanceManager.onHostResume(activity, activity);
			prepareReactApp();
		}
	}

	public void onActivityPaused(NavigationActivity activity) {
		if (reactInstanceManager.hasStartedCreatingInitialContext()) {
			reactInstanceManager.onHostPause(activity);
		}
	}

	public void onActivityDestroyed(NavigationActivity activity) {
		reactInstanceManager.removeReactInstanceEventListener(this);
		if (reactInstanceManager.hasStartedCreatingInitialContext()) {
			reactInstanceManager.onHostDestroy(activity);
		}
	}

	private void prepareReactApp() {
		if (shouldCreateContext()) {
			reactInstanceManager.createReactContextInBackground();
		}
	}

	private void emitAppLaunched(final ReactContext context) {
		if (waitingForAppLaunchEvent) {
			waitingForAppLaunchEvent = false;
			new NavigationEvent(context).appLaunched();
		}
	}

	private boolean shouldCreateContext() {
		return !reactInstanceManager.hasStartedCreatingInitialContext();
	}

	@Override
	public void onReactContextInitialized(final ReactContext context) {
		emitAppLaunched(context);
	}
}

@@ -1668,89 +1668,94 @@
 %0A%09%09%7D
-%0A%09%7D%0A%0A%09private void emitAppLaunched(final ReactContext context) %7B%0A%09%09if (waitingFor
+ else if (waitingForAppLaunchEvent) %7B%0A%09%09%09emitAppLaunched();%0A%09%09%7D%0A%09%7D%0A%0A%09private void emit
 AppL
@@ -1759,26 +1759,23 @@
 ppLaunch
-Event
+ed(
 ) %7B%0A
-%09
 %09%09waitin
@@ -1804,17 +1804,16 @@
 alse;%0A%09%09
-%09
 new Navi
@@ -1824,23 +1824,61 @@
 onEvent(
-c
+reactInstanceManager.getCurrentReactC
 ontext
+()
 ).appLau
@@ -1878,36 +1878,32 @@
 .appLaunched();%0A
-%09%09%7D%0A
 %09%7D%0A%0A%09private boo
@@ -2100,23 +2100,16 @@
 aunched(
-context
 );%0A%09%7D%0A%7D%0A

Revert "Fixes NPE when initializing twice" (#3135)