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"

import groovy.json.JsonSlurper

// https://github.com/callstack/react-native-builder-bob/discussions/359
def registrationCompat = {
  // The new distribution model uses Maven Central https://reactnative.dev/blog/2023/01/12/version-071
  def reactAndroidProject = rootProject.allprojects.find { it.name == 'ReactAndroid' }
  if (reactAndroidProject == null) return false

  def reactNativeManifest = file("${reactAndroidProject.projectDir}/../package.json")
  def reactNativeVersion = new JsonSlurper().parseText(reactNativeManifest.text).version as String
  // Fabric was introduced at react-native@0.68, full CMake support were introduced at react-native@0.70
  // Use Android.mk for compatibility with react-native@0.68/0.69
  reactNativeVersion.matches('(0.68.*|0.69.*)')
}()

def codegenViewLibraryName = "AgoraRtcNg"
def codegenViewModuleName = {
  // Autolink for Fabric uses codegenConfig.name in package.json since react-native@0.70
  // Use codegenViewLibraryName for compatibility with react-native@0.68/0.69
  def libraryManifestJson = new JsonSlurper().parseText(file("$projectDir/../package.json").text)
  registrationCompat ? codegenViewLibraryName : libraryManifestJson.codegenConfig.name
}()

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["AgoraRtcNg_" + name]
}

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

def supportsNamespace() {
  def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
  def major = parsed[0].toInteger()
  def minor = parsed[1].toInteger()

  // Namespace support was added in 7.3.0
  if (major == 7 && minor >= 3) {
    return true
  }

  return major >= 8
}

android {
  if (supportsNamespace()) {
    namespace "io.agora.rtc.ng.react"
    buildFeatures {
      buildConfig true
    }
    sourceSets {
      main {
        manifest.srcFile "src/main/AndroidManifestNew.xml"
      }
    }
  }

  ndkVersion getExtOrDefault("ndkVersion")
  compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault("minSdkVersion")
    targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
    buildConfigField "String", "CODEGEN_MODULE_REGISTRATION", (isNewArchitectureEnabled() && registrationCompat ? "\"${codegenViewModuleName}_registration\"" : "null")

    consumerProguardFiles 'consumer-rules.pro'

    if (isNewArchitectureEnabled() && registrationCompat) {
      def reactAndroidProject = project(':ReactAndroid')
      externalNativeBuild {
        ndkBuild {
          arguments "APP_PLATFORM=android-21",
                    "APP_STL=c++_shared",
                    "NDK_TOOLCHAIN_VERSION=clang",
                    "GENERATED_SRC_DIR=$buildDir/generated/source", // for react_codegen_* in this library's codegen/jni
                    "PROJECT_BUILD_DIR=${appProject.buildDir}", // for REACT_NDK_EXPORT_DIR in ReactAndroid's Android-prebuilt.mk
                    "REACT_ANDROID_DIR=${reactAndroidProject.projectDir}",
                    "REACT_ANDROID_BUILD_DIR=${reactAndroidProject.buildDir}",
                    "CODEGEN_MODULE_NAME=$codegenViewModuleName"
          cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1"
          cppFlags "-std=c++17"
          targets "${codegenViewModuleName}_registration"
        }
      }
    }
  }

  if (isNewArchitectureEnabled() && registrationCompat) {
    // We configure the NDK build only if you decide to opt-in for the New Architecture.
    externalNativeBuild {
      ndkBuild {
        path "Android.mk"
      }
    }
  }

  buildFeatures {
    buildConfig true
  }

  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",
          // This is needed to build Kotlin project with NewArch enabled
          "${project.buildDir}/generated/source/codegen/java"
        ]
      } 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:+"
  implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
  /// dependencies start
  api 'io.agora.rtc:full-screen-sharing:4.5.2.140'
  api 'io.agora.rtc:agora-special-full:4.5.2.140'
  api 'io.agora.rtc:iris-rtc:4.5.2.140-build.4'
  /// dependencies end
}

if (isNewArchitectureEnabled()) {
  react {
    jsRootDir = file("../src/")
    libraryName = codegenViewLibraryName
    codegenJavaPackageName = "io.agora.rtc.ng.react"
  }
}
