buildscript {
  repositories {
    google()
    mavenCentral()
  }

  dependencies {
    classpath "com.android.tools.build:gradle:7.2.1"
  }
}

def isNewArchitectureEnabled() {
  return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true"
}

apply plugin: "com.android.library"


def appProject = rootProject.allprojects.find { it.plugins.hasPlugin('com.android.application') }

if (isNewArchitectureEnabled()) {
  apply plugin: "com.facebook.react"
}

def getExtOrDefault(name) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["RNWhisper_" + name]
}

def getExtOrIntegerDefault(name) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["RNWhisper_" + name]).toInteger()
}

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

// Detect RN Version as done here:
// https://github.com/software-mansion/react-native-reanimated/blob/66a6bd0e3a819ca7ae46751d36e405fe32b68b71/packages/react-native-reanimated/android/build.gradle#L73
def resolveReactNativeDirectory() {
  def reactNativeLocation = rootProject.ext.has("REACT_NATIVE_NODE_MODULES_DIR") ? rootProject.ext.get("REACT_NATIVE_NODE_MODULES_DIR") : null
  if (reactNativeLocation != null) {
    return file(reactNativeLocation)
  }

  // Fallback to node resolver for custom directory structures like monorepos.
  def reactNativePackage = file(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim())
  if(reactNativePackage.exists()) {
    return reactNativePackage.parentFile
  }

  throw new GradleException(
          "[Reanimated] Unable to resolve react-native location in node_modules. You should project extension property (in `app/build.gradle`) `REACT_NATIVE_NODE_MODULES_DIR` with path to react-native."
  )
}

def reactNativeRootDir = resolveReactNativeDirectory()

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

def REACT_NATIVE_VERSION = reactProperties.getProperty("VERSION_NAME")
def REACT_NATIVE_MINOR_VERSION = REACT_NATIVE_VERSION.startsWith("0.0.0-") ? 1000 : REACT_NATIVE_VERSION.split("\\.")[1].toInteger()

android {
  def agpVersion = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION
  if (agpVersion.tokenize('.')[0].toInteger() >= 7) {
    namespace "com.rnwhisper"
  }
  ndkVersion getExtOrDefault("ndkVersion")
  compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault("minSdkVersion")
    targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
    externalNativeBuild {
      cmake {
        abiFilters (*reactNativeArchitectures())
        // Configure STL to be compatible with ReactAndroid JSI libraries
        arguments "-DANDROID_STL=c++_shared",
                  "-DREACT_NATIVE_MINOR_VERSION=${REACT_NATIVE_MINOR_VERSION}",
                  "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
      }
    }
    ndk {
      // Ensure shared STL is used for JSI compatibility
      abiFilters (*reactNativeArchitectures())
    }
  }

  packagingOptions {
    doNotStrip resolveBuildType() == "debug" ? "**/**/*.so" : ""
    excludes = [
      "META-INF",
      "META-INF/**",
      "**/libc++_shared.so",
      "**/libfbjni.so",
      "**/libjsi.so",
      "**/libfolly_json.so",
      "**/libfolly_runtime.so",
      "**/libglog.so",
      "**/libreactnative.so",
      "**/libreactnativejni.so",
      "**/libturbomodulejsijni.so",
      "**/libreact_nativemodule_core.so",
    ]
  }

  buildFeatures {
    prefab = true
  }
  externalNativeBuild {
    cmake {
      path = file('src/main/CMakeLists.txt')
    }
  }
  // Exclude jniLibs when building from source
  sourceSets {
    main {
      jniLibs.srcDirs = []
    }
  }
  buildTypes {
    release {
      minifyEnabled false
    }
  }

  lintOptions {
    disable "GradleCompatible"
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

  sourceSets {
    main {
      if (isNewArchitectureEnabled()) {
        java.srcDirs += ['src/newarch']
      } else {
        java.srcDirs += ['src/oldarch']
      }
    }
  }
}

repositories {
  mavenCentral()
  google()
}


dependencies {
  // For < 0.71, this will be from the local maven repo
  // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin
  //noinspection GradleDynamicVersion
  implementation "com.facebook.react:react-native:+"
}

if (isNewArchitectureEnabled()) {
  react {
    jsRootDir = file("../src/")
    libraryName = "RNWhisper"
    codegenJavaPackageName = "com.rnwhisper"
  }
}

def resolveBuildType() {
    Gradle gradle = getGradle()
    String tskReqStr = gradle.getStartParameter().getTaskRequests()["args"].toString()

    return tskReqStr.contains("Release") ? "release" : "debug"
}
