import java.nio.file.Paths

buildscript {
  repositories {
    google()
    mavenCentral()
  }

  dependencies {
    classpath "com.android.tools.build:gradle:7.2.2"
  }
}

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 getExtOrDefault(name) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["Tflite_" + name]
}

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

static def findNodeModules(baseDir) {
  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 nodeModulesPath = Paths.get(basePath.toString(), "node_modules")
    def reactNativePath = Paths.get(nodeModulesPath.toString(), "react-native")
    if (nodeModulesPath.toFile().exists() && reactNativePath.toFile().exists()) {
      return nodeModulesPath.toString()
    }
    basePath = basePath.getParent()
  }
  throw new GradleException("react-native-fast-tflite: Failed to find node_modules/ path!")
}

def nodeModules = findNodeModules(projectDir)

android {
  ndkVersion getExtOrDefault("ndkVersion")
  compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
  namespace "com.tflite"

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault("minSdkVersion")
    targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
    externalNativeBuild {
      cmake {
        arguments "-DANDROID_STL=c++_shared",
                "-DNODE_MODULES_DIR=${nodeModules}",
                "-DIS_NEW_ARCHITECTURE_ENABLED=${isNewArchitectureEnabled()}"
        cppFlags "-O2 -frtti -fexceptions -Wall -fstack-protector-all"
        abiFilters "x86", "x86_64", "armeabi-v7a", "arm64-v8a"
      }
    }
  }
  externalNativeBuild {
    cmake {
      path "CMakeLists.txt"
    }
  }
  packagingOptions {
    excludes = [
            "META-INF",
            "META-INF/**",
            "**/libc++_shared.so",
            "**/libfbjni.so",
            "**/libjsi.so",
            "**/libreactnativejni.so",
            "**/libturbomodulejsijni.so",
            "**/libreact_nativemodule_core.so",
    ]
  }
  buildTypes {
    release {
      minifyEnabled false
    }
  }

  buildFeatures {
    prefab true
  }

  lintOptions {
    disable "GradleCompatible"
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

  configurations {
    extractHeaders
    extractSO
  }
}

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:+"

  // Tensorflow Lite .aar (includes C API via prefabs)
  implementation "org.tensorflow:tensorflow-lite:2.12.0"
  extractHeaders("org.tensorflow:tensorflow-lite:2.12.0")
  extractSO("org.tensorflow:tensorflow-lite:2.12.0")
}

task extractAARHeaders {
  doLast {
    configurations.extractHeaders.files.each {
      def file = it.absoluteFile
      def packageName = file.name.tokenize('-')[0]
      copy {
        from zipTree(file)
        into "src/main/cpp/lib/$packageName/"
        include "**/*.h"
      }
    }
  }
}

task extractSOFiles {
  doLast {
    configurations.extractSO.files.each {
      def file = it.absoluteFile
      def packageName = file.name.tokenize('-')[0]
      copy {
        from zipTree(file)
        into "src/main/cpp/lib/$packageName/"
        include "jni/**/*.so"
      }
    }
  }
}

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


def nativeBuildDependsOn(dependsOnTask) {
  def buildTasks = tasks.findAll({ task -> (
          !task.name.contains("Clean")
                  && (task.name.contains("externalNative")
                  || task.name.contains("CMake")
                  || task.name.contains("generateJsonModel")
          )
  ) })
  buildTasks.forEach { task -> task.dependsOn(dependsOnTask) }
}

afterEvaluate {
  nativeBuildDependsOn(extractAARHeaders)
  nativeBuildDependsOn(extractSOFiles)
}
