import java.nio.file.Paths

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"


def appProject = rootProject.allprojects.find { it.plugins.hasPlugin('com.android.application') }

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

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

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

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

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 reactNativeFromNodeModulesWithReanimated = file("${projectDir}/../../react-native")
  if (reactNativeFromNodeModulesWithReanimated.exists()) {
    return reactNativeFromNodeModulesWithReanimated
  }

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


def found = false
def basePath = projectDir.toPath().normalize()

// Find node_modules inside the example project
def nodeModulesDir = Paths.get(basePath.getParent().toString(), "example/node_modules")
def reactNativeDir = Paths.get(nodeModulesDir.toString(), "react-native/android")
if (nodeModulesDir.toFile().exists() && reactNativeDir.toFile().exists()) {
  found = true
}

if(!found){
  // Node's module resolution algorithm searches up to the root directory,
  // after which the base path will be null
  while (basePath) {
    nodeModulesDir = Paths.get(basePath.toString(), "node_modules")
    reactNativeDir = Paths.get(nodeModulesDir.toString(), "react-native/android")
    if (nodeModulesDir.toFile().exists() && reactNativeDir.toFile().exists()) {
      found = true
      break;
    }
    basePath = basePath.getParent()
  }
}

if(!found) {
  throw new GradleException(
    "${project.name}: unable to locate React Native android sources. " +
      "Ensure you have you installed React Native as a dependency in your project and try again.")
}

def nodeModulesPath = nodeModulesDir.toString().replace("\\", "/")
def reactNativePath = reactNativeDir.toString().replace("\\", "/")


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 "com.gifsicle"
  } else {
    sourceSets {
      main {
        manifest.srcFile "src/main/AndroidManifestDeprecated.xml"
      }
    }
  }

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

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault("minSdkVersion")
    targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
    externalNativeBuild {
      cmake {
        cppFlags "-fexceptions", "-frtti", "-std=c++1y", "-DONANDROID"
        abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a'
        arguments '-DANDROID_STL=c++_shared',
          "-DNODE_MODULES_DIR=${nodeModulesPath}",
          "-DREACT_NATIVE_MINOR_VERSION=${REACT_NATIVE_MINOR_VERSION}"
      }
    }
  }
  externalNativeBuild {
    cmake {
      path "CMakeLists.txt"
    }
  }

  packagingOptions {
    excludes = [
      "**/libc++_shared.so",
      "**/libfbjni.so",
      "**/libreactnativejni.so",
      "**/libjsi.so",
      "**/libreact_nativemodule_core.so",
      "**/libturbomodulejsijni.so",
      "**/MANIFEST.MF",
      ""
    ]
    doNotStrip '**/*.so'
  }

  buildTypes {
    debug {
      packagingOptions {
        doNotStrip '**/*.so'
      }
      minifyEnabled false
      debuggable true
      jniDebuggable true
      renderscriptDebuggable true
    }
    release {
      minifyEnabled false
    }
  }
  buildFeatures {
    prefab true
  }
  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:+"
}

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