import groovy.json.JsonSlurper
import java.nio.file.Paths

apply plugin: 'com.android.library'

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

android {
    compileSdkVersion 35

    def agpVersion = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION
    if (agpVersion.tokenize('.')[0].toInteger() >= 7) {
        namespace "com.imagepicker"
    }

    // Used to override the NDK path/version on internal CI or by allowing
    // users to customize the NDK path/version from their root project (e.g. for M1 support)
    if (rootProject.hasProperty("ndkPath")) {
        ndkPath rootProject.ext.ndkPath
    }
    if (rootProject.hasProperty("ndkVersion")) {
        ndkVersion rootProject.ext.ndkVersion
    }

    defaultConfig {
        minSdkVersion safeExtGet('minSdkVersion', 24)
        targetSdkVersion 34
        versionCode 1
        versionName "1.0"
        buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
    }

    buildTypes {
        release {
            minifyEnabled false
        }
    }

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

repositories {
  maven {
    // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
    url "${rootDir}/../node_modules/react-native/android"
  }
  mavenCentral()
  google()
}

dependencies {
    if (isNewArchitectureEnabled() && getReactNativeMinorVersion() < 71) {
      implementation project(":ReactAndroid")
    } else {
      implementation 'com.facebook.react:react-native:+' // from node_modules
    }

    implementation "androidx.core:core:1.3.1"
    implementation "androidx.exifinterface:exifinterface:1.3.3"
}

def isNewArchitectureEnabled() {
    // To opt-in for the New Architecture, you can either:
    // - Set `newArchEnabled` to true inside the `gradle.properties` file
    // - Invoke gradle with `-newArchEnabled=true`
    // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
    return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

static def findNodeModulePath(baseDir, packageName) {
  def basePath = baseDir.toPath().normalize()
  // Node's module resolution algorithm searches up to the root directory,
  // after which the base path will be null
  while (basePath) {
    def candidatePath = Paths.get(basePath.toString(), "node_modules", packageName)
    if (candidatePath.toFile().exists()) {
      return candidatePath.toString()
    }
    basePath = basePath.getParent()
  }
  return null
}

def findNodeModulePath(packageName) {
  // Don't start in the project dir, as its path ends with node_modules/react-native-mlkit-ocr/android
  // we want to go two levels up, so we end up in the first_node modules and eventually
  // search upwards if the package is not found there
  return findNodeModulePath(projectDir.toPath().parent.parent.toFile(), packageName)
}

def safeExtGet(prop, fallback) {
    rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
}

def resolveReactNativeDirectory() {
    def reactNativeLocation = safeExtGet("REACT_NATIVE_NODE_MODULES_DIR", null)
    if (reactNativeLocation != null) {
        return file(reactNativeLocation)
    }

    // monorepo workaround
    // react-native can be hoisted or in project's own node_modules
    def reactNativeFromProjectNodeModules = file("${rootProject.projectDir}/../node_modules/react-native")
    if (reactNativeFromProjectNodeModules.exists()) {
        return reactNativeFromProjectNodeModules
    }

    def reactNativeFromNodeModulesWithImagePicker = file("${projectDir}/../../react-native")
    if (reactNativeFromNodeModulesWithImagePicker.exists()) {
        return reactNativeFromNodeModulesWithImagePicker
    }

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

def getReactNativeMinorVersion() {
    def REACT_NATIVE_DIR = resolveReactNativeDirectory()

    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_MINOR_VERSION = REACT_NATIVE_VERSION.startsWith("0.0.0-") ? 1000 : REACT_NATIVE_VERSION.split("\\.")[1].toInteger()

    return REACT_NATIVE_MINOR_VERSION
}