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

def reactNativeMinorVersion() {
  // node_modules may be at rootDir (monorepo) or rootDir/.. (standard RN project)
  def locations = [
    new File(rootDir, "node_modules/react-native/package.json"),
    new File(rootDir, "../node_modules/react-native/package.json"),
  ]
  for (location in locations) {
    if (location.exists()) {
      def json = new groovy.json.JsonSlurper().parseText(location.text)
      def version = json.version as String
      return version.tokenize('.')[1].toInteger()
    }
  }
  return 0
}

def shouldApplyReactPlugin() {
  // RN 0.82+ always uses new arch, so always apply the plugin
  // For older versions, only apply when newArchEnabled=true
  return reactNativeMinorVersion() >= 82 || isNewArchitectureEnabled()
}

apply plugin: "com.android.library"
apply plugin: "org.jetbrains.kotlin.android"

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

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

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

def supportsNamespace() {
  def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
  def major = parsed[0].toInteger()
  def minor = parsed[1].toInteger()
  return (major == 7 && minor >= 3) || major >= 8
}

android {
  if (supportsNamespace()) {
    namespace "com.launcherkit"

    buildFeatures {
      buildConfig true
    }
  }

  compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")

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

  buildTypes {
    release {
      minifyEnabled false
    }
  }

  lintOptions {
    disable "GradleCompatible"
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

  sourceSets {
    main {
      if (shouldApplyReactPlugin()) {
        java.srcDirs += [
          "generated/java",
          "generated/jni"
        ]
      }
    }
  }
}

repositories {
  mavenCentral()
  google()
}

def kotlin_version = getExtOrDefault("kotlinVersion")

dependencies {
  //noinspection GradleDynamicVersion
  implementation "com.facebook.react:react-android:+"
  implementation "androidx.palette:palette:1.0.0"
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

if (shouldApplyReactPlugin()) {
  react {
    jsRootDir = file("../src/")
    libraryName = "RNLauncherKitSpec"
    codegenJavaPackageName = "com.launcherkit"
  }
}
