apply plugin: 'com.android.library'

group = 'host.exp.exponent'
version = '1.12.26'

def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
apply from: expoModulesCorePlugin
applyKotlinExpoModulesCorePlugin()
useDefaultAndroidSdkVersions()
useExpoPublishing()

def isExpoModulesCoreTests = {
  Gradle gradle = getGradle()
  String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()
  if (tskReqStr =~ /:expo-modules-core:connected\w*AndroidTest/) {
    def androidTests = project.file("src/androidTest")
    return androidTests.exists() && androidTests.isDirectory()
  }
  return false
}.call()

def REACT_NATIVE_BUILD_FROM_SOURCE = findProject(":packages:react-native:ReactAndroid") != null
def REACT_NATIVE_DIR = REACT_NATIVE_BUILD_FROM_SOURCE
  ? findProject(":packages:react-native:ReactAndroid").getProjectDir().parent
  : file(providers.exec {
      workingDir(rootDir)
      commandLine("node", "--print", "require.resolve('react-native/package.json')")
    }.standardOutput.asText.get().trim()).parent

def reactProperties = new Properties()
file("$REACT_NATIVE_DIR/ReactAndroid/gradle.properties").withInputStream { reactProperties.load(it) }

def REACT_NATIVE_VERSION = reactProperties.getProperty("VERSION_NAME")
def REACT_NATIVE_TARGET_VERSION = REACT_NATIVE_VERSION.split("\\.")[1].toInteger()

def reactNativeArchitectures() {
  def value = project.getProperties().get("reactNativeArchitectures")
  return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

// HERMES
def USE_HERMES = true
if (findProject(":app")) {
  def appProject = project(":app")
  USE_HERMES = appProject?.hermesEnabled?.toBoolean() || appProject?.ext?.react?.enableHermes?.toBoolean()
}

// Currently the needs for hermes/jsc are only for androidTest, so we turn on this flag only when `isExpoModulesCoreTests` is true
USE_HERMES = USE_HERMES && isExpoModulesCoreTests
// END HERMES

def isNewArchitectureEnabled = findProperty("newArchEnabled") == "true"

android {
  if (rootProject.hasProperty("ndkPath")) {
    ndkPath rootProject.ext.ndkPath
  }
  if (rootProject.hasProperty("ndkVersion")) {
    ndkVersion rootProject.ext.ndkVersion
  }

  namespace "expo.modules"
  defaultConfig {
    consumerProguardFiles 'proguard-rules.pro'
    versionCode 1
    versionName "1.12.26"
    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled.toString()

    testInstrumentationRunner "expo.modules.TestRunner"

    externalNativeBuild {
      cmake {
        abiFilters (*reactNativeArchitectures())
        arguments "-DANDROID_STL=c++_shared",
          "-DREACT_NATIVE_DIR=${REACT_NATIVE_DIR}",
          "-DREACT_NATIVE_TARGET_VERSION=${REACT_NATIVE_TARGET_VERSION}",
          "-DUSE_HERMES=${USE_HERMES}",
          "-DIS_NEW_ARCHITECTURE_ENABLED=${isNewArchitectureEnabled}",
          "-DUNIT_TEST=${isExpoModulesCoreTests}"
      }
    }
  }

  externalNativeBuild {
    cmake {
      path "CMakeLists.txt"
    }
  }

  buildFeatures {
    buildConfig true
    prefab true
  }

  packagingOptions {
    // Gradle will add cmake target dependencies into packaging.
    // Theses files are intermediated linking files to build modules-core and should not be in final package.
    def sharedLibraries = [
      "**/libc++_shared.so",
      "**/libfabricjni.so",
      "**/libfbjni.so",
      "**/libfolly_json.so",
      "**/libfolly_runtime.so",
      "**/libglog.so",
      "**/libhermes.so",
      "**/libjscexecutor.so",
      "**/libjsi.so",
      "**/libreactnativejni.so",
      "**/libreact_debug.so",
      "**/libreact_nativemodule_core.so",
      "**/libreact_render_debug.so",
      "**/libreact_render_graphics.so",
      "**/libreact_render_core.so",
      "**/libreact_render_componentregistry.so",
      "**/libreact_render_mapbuffer.so",
      "**/librrc_view.so",
      "**/libruntimeexecutor.so",
      "**/libyoga.so",
    ]

    // Required or mockk will crash
    resources {
      excludes += [
          "META-INF/LICENSE.md",
          "META-INF/LICENSE-notice.md"
      ]
    }

    // In android (instrumental) tests, we want to package all so files to enable our JSI functionality.
    // Otherwise, those files should be excluded, because will be loaded by the application.
    if (isExpoModulesCoreTests) {
      pickFirsts += sharedLibraries
    } else {
      excludes += sharedLibraries
    }
  }


  testOptions {
    unitTests.includeAndroidResources = true

    unitTests.all { test ->
      testLogging {
        outputs.upToDateWhen { false }
        events "passed", "failed", "skipped", "standardError"
        showCauses true
        showExceptions true
        showStandardStreams true
      }
    }
  }
}

dependencies {
  implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${kotlinVersion()}"
  implementation "org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion()}"
  implementation 'androidx.annotation:annotation:1.7.1'

  api "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0"
  api "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4"
  api "androidx.core:core-ktx:1.12.0"

  implementation("androidx.tracing:tracing-ktx:1.2.0")

  implementation 'com.facebook.react:react-android'

  compileOnly 'com.facebook.fbjni:fbjni:0.5.1'

  testImplementation 'androidx.test:core:1.5.0'
  testImplementation 'junit:junit:4.13.2'
  testImplementation 'io.mockk:mockk:1.13.10'
  testImplementation "com.google.truth:truth:1.1.2"
  testImplementation "org.robolectric:robolectric:4.11.1"
  testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.0"
  testImplementation "org.json:json:20230227"

  androidTestImplementation 'androidx.test:runner:1.5.2'
  androidTestImplementation 'androidx.test:core:1.5.0'
  androidTestImplementation 'androidx.test:rules:1.5.0'
  androidTestImplementation "io.mockk:mockk-android:1.13.10"
  androidTestImplementation "com.google.truth:truth:1.1.2"
  androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.0"

  if (isExpoModulesCoreTests) {
    if (USE_HERMES) {
      compileOnly "com.facebook.react:hermes-android"
    } else {
      compileOnly "org.webkit:android-jsc:+"
    }
  }
}
