buildscript {
  // The Android Gradle plugin is only required when opening the android folder stand-alone.
  // This avoids unnecessary downloads and potential conflicts when the library is included as a
  // module dependency in an application project.
  if (project == rootProject) {
      repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }

    dependencies {
      classpath("com.android.tools.build:gradle:7.4.2")
    }
  }
}

def getExtOrInitialValue(name, initialValue) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : initialValue
}

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

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

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

def resolveReactNativeDirectory() {
  def reactNativeLocation = getExtOrInitialValue("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(
          providers.exec {
              workingDir(rootDir)
              commandLine("node", "--print", "require.resolve('react-native/package.json')")
          }.standardOutput.asText.get().trim()
  )
  if (reactNativePackage.exists()) {
    return reactNativePackage.parentFile
  }

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

  throw new Exception(
          "[react-native-netinfo] 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
}


apply plugin: 'com.android.library'

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

android {
  compileSdkVersion getExtOrIntegerDefault('compileSdkVersion')

  def agpVersion = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION
  // Check AGP version for backward compatibility reasons
  if (agpVersion.tokenize('.')[0].toInteger() >= 7) {
    namespace = "com.reactnativecommunity.netinfo"
  }

  compileOptions {
      sourceCompatibility JavaVersion.VERSION_1_8
      targetCompatibility JavaVersion.VERSION_1_8
  }

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault('minSdkVersion')
    targetSdkVersion getExtOrIntegerDefault('targetSdkVersion')
    buildConfigField("boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString())
  }
  sourceSets {
    main {
        if (isNewArchitectureEnabled()) {
            java.srcDirs += ['src/newarch']
        } else {
            java.srcDirs += ['src/oldarch']
        }
      }
  }
  lintOptions{
    abortOnError false
  }

}

repositories {
  maven {
    // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm

    // Use node resolver to locate react-native package
    def reactNativePackage = file(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim())
    if (reactNativePackage.exists()) {
      url "$reactNativePackage.parentFile/android"
    }
    // Fallback to react-native package colocated in node_modules
    else {
      url "$rootDir/../node_modules/react-native/android"
    }
  }
  google()
  mavenLocal()
  mavenCentral()
}

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