// Copyright 2004-present Facebook. All Rights Reserved.

package com.facebook.react.bridge;

import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.inject.Provider;

import java.util.concurrent.atomic.AtomicInteger;

import com.facebook.infer.annotation.Assertions;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.react.module.model.ReactModuleInfo;
import com.facebook.systrace.SystraceMessage;

import static com.facebook.infer.annotation.Assertions.assertNotNull;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_MODULE_END;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_MODULE_START;
import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE;

/**
 * Holder to enable us to lazy create native modules.
 *
 * This works by taking a provider instead of an instance, when it is first required we'll create
 * and initialize it. Initialization currently always happens on the UI thread but this is due to
 * change for performance reasons.
 *
 * Lifecycle events via a {@link LifecycleEventListener} will still always happen on the UI thread.
 */
@DoNotStrip
public class ModuleHolder {

  private static final AtomicInteger sInstanceKeyCounter = new AtomicInteger(1);

  private final String mName;
  private final boolean mCanOverrideExistingModule;
  private final boolean mHasConstants;

  private @Nullable Provider<? extends NativeModule> mProvider;
  // Outside of the constructur, these should only be checked or set when synchronized on this
  private @Nullable @GuardedBy("this") NativeModule mModule;

  // These are used to communicate phases of creation and initialization across threads
  private @GuardedBy("this") boolean mInitializable;
  private @GuardedBy("this") boolean mIsCreating;
  private @GuardedBy("this") boolean mIsInitializing;

  public ModuleHolder(ReactModuleInfo moduleInfo, Provider<? extends NativeModule> provider) {
    mName = moduleInfo.name();
    mCanOverrideExistingModule = moduleInfo.canOverrideExistingModule();
    mHasConstants = moduleInfo.hasConstants();
    mProvider = provider;
    if (moduleInfo.needsEagerInit()) {
      mModule = create();
    }
  }

  public ModuleHolder(NativeModule nativeModule) {
    mName = nativeModule.getName();
    mCanOverrideExistingModule = nativeModule.canOverrideExistingModule();
    mHasConstants = true;
    mModule = nativeModule;
  }

  /*
  * Checks if mModule has been created, and if so tries to initialize the module unless another
  * thread is already doing the initialization.
  * If mModule has not been created, records that initialization is needed
  */
  /* package */ void markInitializable() {
    boolean shouldInitializeNow = false;
    NativeModule module = null;
    synchronized (this) {
      mInitializable = true;
      if (mModule != null) {
        Assertions.assertCondition(!mIsInitializing);
        shouldInitializeNow = true;
        module = mModule;
      }
    }
    if (shouldInitializeNow) {
      doInitialize(module);
    }
  }

  /* pacakge */ synchronized boolean hasInstance() {
    return mModule != null;
  }

  public synchronized void destroy() {
    if (mModule != null) {
      mModule.onCatalystInstanceDestroy();
    }
  }

  @DoNotStrip
  public String getName() {
    return mName;
  }

  public boolean getCanOverrideExistingModule() {
    return mCanOverrideExistingModule;
  }

  public boolean getHasConstants() {
    return mHasConstants;
  }

  @DoNotStrip
  public NativeModule getModule() {
    NativeModule module;
    boolean shouldCreate = false;
    synchronized (this) {
      if (mModule != null) {
        return mModule;
      // if mModule has not been set, and no one is creating it. Then this thread should call create
      } else if (!mIsCreating) {
        shouldCreate = true;
        mIsCreating = true;
      } else  {
        // Wait for mModule to be created by another thread
      }
    }
    if (shouldCreate) {
      module = create();
      // Once module is built (and initialized if markInitializable has been called), modify mModule
      // And signal any waiting threads that it is acceptable to read the field now
      synchronized (this) {
        mIsCreating = false;
        this.notifyAll();
      }
      return module;
    } else {
      synchronized (this) {
        // Block waiting for another thread to build mModule instance
        // Since mIsCreating is true until after creation and instantiation (if needed), we wait
        // until the module is ready to use.
        while (mModule == null && mIsCreating) {
          try {
            this.wait();
          } catch (InterruptedException e) {
            continue;
          }
        }
        return Assertions.assertNotNull(mModule);
      }
    }
  }

  private NativeModule create() {
    SoftAssertions.assertCondition(mModule == null, "Creating an already created module.");
    int instanceKey = sInstanceKeyCounter.getAndIncrement();
    ReactMarker.logMarker(CREATE_MODULE_START, mName, instanceKey);
    SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ModuleHolder.createModule")
      .arg("name", mName)
      .flush();
    NativeModule module;
    try {
      module = assertNotNull(mProvider).get();
      mProvider = null;
      boolean shouldInitializeNow = false;
      synchronized(this) {
        mModule = module;
        if (mInitializable && !mIsInitializing) {
          shouldInitializeNow = true;
        }
      }
      if (shouldInitializeNow) {
        doInitialize(module);
      }
    } finally {
      ReactMarker.logMarker(CREATE_MODULE_END, instanceKey);
      SystraceMessage.endSection(TRACE_TAG_REACT_JAVA_BRIDGE).flush();
    }
    return module;
  }

  private void doInitialize(NativeModule module) {
    SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ModuleHolder.initialize")
      .arg("name", mName)
      .flush();
    ReactMarker.logMarker(ReactMarkerConstants.INITIALIZE_MODULE_START, mName);
    try {
      boolean shouldInitialize = false;
      // Check to see if another thread is initializing the object, if not claim the responsibility
      synchronized (this) {
        if (mInitializable && !mIsInitializing) {
          shouldInitialize = true;
          mIsInitializing = true;
        }
      }
      if (shouldInitialize) {
        module.initialize();
        // Once finished, set flags accordingly, but we don't expect anyone to wait for this to finish
        // So no need to notify other threads
        synchronized (this) {
          mIsInitializing = false;
        }
      }
    } finally {
      ReactMarker.logMarker(ReactMarkerConstants.INITIALIZE_MODULE_END);
      SystraceMessage.endSection(TRACE_TAG_REACT_JAVA_BRIDGE).flush();
    }
  }
}

@@ -1283,16 +1283,91 @@
 er(1);%0A%0A
+  private final int mInstanceKey = sInstanceKeyCounter.getAndIncrement();%0A%0A
   privat
@@ -5024,69 +5024,8 @@
 %22);%0A
-    int instanceKey = sInstanceKeyCounter.getAndIncrement();%0A
     
@@ -5074,17 +5074,18 @@
  mName, 
-i
+mI
 nstanceK
@@ -5664,17 +5664,18 @@
 LE_END, 
-i
+mI
 nstanceK
@@ -6039,16 +6039,30 @@
 T, mName
+, mInstanceKey
 );%0A    t
@@ -6670,32 +6670,32 @@
     %7D finally %7B%0A
-
       ReactMarke
@@ -6748,16 +6748,30 @@
 DULE_END
+, mInstanceKey
 );%0A     

tag INITIALIZE_MODULE marker with the non-zero instance key