def kotlinVersion =
  rootProject.ext.has("kotlinVersion")
    ? rootProject.ext.get("kotlinVersion")
    : project.properties["StreamChatExpo_kotlinVersion"]

buildscript {
  repositories {
    google()
    mavenCentral()
  }

  dependencies {
    classpath "com.android.tools.build:gradle:7.2.1"
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
  }
}

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

apply plugin: "com.android.library"
// AGP 9 ships built-in Kotlin support and registers the `kotlin` extension
// itself. Applying the Kotlin plugin on top of it fails configuration with
// "Cannot add extension with name 'kotlin'". Only apply it when nothing has
// registered that extension yet.
if (project.extensions.findByName('kotlin') == null) {
    apply plugin: "kotlin-android"
}

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

def getExtOrIntegerDefault(name) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["StreamChatExpo_" + name]).toInteger()
}
def canonicalProjectDir = projectDir.getCanonicalFile()
def localSharedNativeRootDir = new File(projectDir, "src/main/java/com/streamchatreactnative/shared")
def sharedNativeRootDir = new File(canonicalProjectDir, "../../shared-native/android")
def hasNativeSources = { File dir ->
  dir.exists() && !fileTree(dir).matching { include "**/*.kt"; include "**/*.java" }.files.isEmpty()
}

// The agent components' sign-ins open in the browser's Auth Tab, which needs androidx.browser
// 1.9.0, and that needs the app to build with compileSdk 36 and AGP 8.9.1. An app below either
// gets 1.8.0 and opens them in a Custom Tab instead, so the SDK asks neither of anyone.
def versionAtLeast = { String version, List<Integer> wanted ->
  def parts = version.tokenize('.-').collect { it.replaceAll(/\D.*$/, '') }.findAll { it }.collect { it.toInteger() }
  for (int i = 0; i < wanted.size(); i++) {
    def part = i < parts.size() ? parts[i] : 0
    if (part != wanted[i]) return part > wanted[i]
  }
  return true
}
def agentSignInWithAuthTab =
  getExtOrIntegerDefault("compileSdkVersion").toString().toInteger() >= 36 &&
    versionAtLeast(com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION, [8, 9, 1])
def agentSignInVariant = agentSignInWithAuthTab ? "authtab" : "customtabs"
def sharedAgentSignInDir = new File(canonicalProjectDir, "../../shared-native/android-${agentSignInVariant}")
def agentSignInDir = hasNativeSources(sharedAgentSignInDir)
  ? sharedAgentSignInDir
  : new File(projectDir, "src/agent-sign-in/${agentSignInVariant}")

android {
  compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
  def agpVersion = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION
  def agpMajorVersion = agpVersion.tokenize('.')[0].toInteger()
  def agpMinorVersion = agpVersion.tokenize('.')[1].toInteger()

  if (agpMajorVersion >= 7 && agpMinorVersion >= 3) {
    namespace "com.streamchatexpo"
  }

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault("minSdkVersion")
    targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
  }

  buildTypes {
    release {
      minifyEnabled false
    }
  }

  lintOptions {
    disable "GradleCompatible"
  }

  compileOptions {
    // Must match the Kotlin jvmTarget set on the KotlinCompile tasks below: an inconsistent
    // JVM-target between the Java and Kotlin compilation tasks fails the build. On AGP 9 this
    // is also what AGP's built-in Kotlin derives the Kotlin jvmTarget from.
    sourceCompatibility JavaVersion.VERSION_17
    targetCompatibility JavaVersion.VERSION_17
  }

  sourceSets {
    main {
      if (isNewArchitectureEnabled()) {
        java.srcDirs += [
          "src/newarch",
          "src/main/java/com/streamchatreactnative/shared",
          agentSignInDir,
          "${project.buildDir}/generated/source/codegen/java"
        ]
      }
    }
  }
}

tasks.register("syncSharedShimmerSources") {
  outputs.dir(localSharedNativeRootDir)
  outputs.upToDateWhen { false }
  doLast {
    def sourceRootDir = null
    if (hasNativeSources(sharedNativeRootDir)) {
      sourceRootDir = sharedNativeRootDir
    } else if (hasNativeSources(localSharedNativeRootDir)) {
      sourceRootDir = localSharedNativeRootDir
    }

    if (sourceRootDir == null) {
      throw new GradleException(
        "Missing shared native Android sources. Expected either src/main/java/com/streamchatreactnative/shared/**/*.{kt,java} " +
          "or ../../shared-native/android/**/*.{kt,java}."
      )
    }

    if (sourceRootDir != localSharedNativeRootDir) {
      project.delete(localSharedNativeRootDir)
      project.copy {
        from(sourceRootDir)
        into(localSharedNativeRootDir)
      }
    } else if (!hasNativeSources(localSharedNativeRootDir)) {
      throw new GradleException("Shared native source directory exists but has no Kotlin/Java files.")
    }
  }
}

tasks.matching { it.name == "preBuild" }.configureEach {
  dependsOn("syncSharedShimmerSources")
}

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
  dependsOn("syncSharedShimmerSources")
  // Set here rather than via `android.kotlinOptions`: that DSL is contributed by the Kotlin
  // Gradle plugin, which is deliberately not applied when AGP registers the `kotlin`
  // extension itself (see the guard at the top of this file). This form works either way.
  compilerOptions {
    jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
  }
}

repositories {
  mavenCentral()
  google()
}

dependencies {
  implementation "com.facebook.react:react-native:+"
  // The agent components' tool-call sign-ins: an Auth Tab where the app's build allows 1.9.0,
  // else a Custom Tab (see `agentSignInWithAuthTab`).
  implementation "androidx.browser:browser:${agentSignInWithAuthTab ? '1.9.0' : '1.8.0'}"
}

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

if (isNewArchitectureEnabled()) {
  gradle.projectsEvaluated {
    if (rootProject.ext.has("streamChatReactNativeCodegenHookInstalled")) {
      return
    }

    def androidAppProject = rootProject.subprojects.find { it.plugins.hasPlugin("com.android.application") }
    if (androidAppProject == null) {
      return
    }

    def dependencyCodegenTasks = rootProject.subprojects
      .findAll { it != androidAppProject }
      .collect { it.tasks.findByName("generateCodegenArtifactsFromSchema") }
      .findAll { it != null }

    if (dependencyCodegenTasks.isEmpty()) {
      return
    }

    rootProject.ext.set("streamChatReactNativeCodegenHookInstalled", true)

    androidAppProject.tasks.matching { task ->
      task.name.startsWith("configureCMake")
    }.configureEach {
      dependsOn(dependencyCodegenTasks)
    }
  }
}
