import java.nio.file.Paths

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("SKRNMLKitFaceDetection: Failed to find node_modules/ path!")
}

def nodeModules = findNodeModules(projectDir)
logger.warn("ReactNativeMLKitFaceDetection: node_modules/ found at: ${nodeModules}")

def hasVisionCamera = file("${nodeModules}/react-native-vision-camera/package.json").exists()
def hasNativeVideo = file("${nodeModules}/react-native-native-video/package.json").exists()
if(hasNativeVideo) {
  logger.warn("Has react-native-native-video :)")
}
def reactProperties = new Properties()
file("$nodeModules/react-native/ReactAndroid/gradle.properties").withInputStream { reactProperties.load(it) }
def REACT_NATIVE_VERSION = reactProperties.getProperty("VERSION_NAME").split("\\.")[1].toInteger()

//def reactNative = new File("$nodeModules/react-native")

buildscript {
    if (project == rootProject) {
        repositories {
            google()
            mavenCentral()
            jcenter()
        }

        dependencies {
            classpath 'com.android.tools.build:gradle:3.5.3'
        }
    }
}

apply plugin: 'com.android.library'

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


// This is how the NODE_MODULES_DIR magic variable appears in our CMAKELISTS file
String[] cmakeArgs;
if(hasNativeVideo) {
  cmakeArgs = ["-DNODE_MODULES_DIR=${nodeModules}",
                  // This is how the REACT_NATIVE_VERSION magic variable appears in our CMAKELISTS file
                  "-DREACT_NATIVE_VERSION=${REACT_NATIVE_VERSION}",
  "-DHAS_RN_NATIVE_VIDEO=1"]
}
else {
  cmakeArgs = ["-DNODE_MODULES_DIR=${nodeModules}",
               // This is how the REACT_NATIVE_VERSION magic variable appears in our CMAKELISTS file
               "-DREACT_NATIVE_VERSION=${REACT_NATIVE_VERSION}"]
}

def getExtOrDefaultValue(name, defaultValue) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : defaultValue
}


android {
    compileSdkVersion safeExtGet('MlkitFaceDetection_compileSdkVersion', 29)
    ndkVersion getExtOrDefaultValue('ndkVersion', '21.4.7075529')
    
    defaultConfig {
        minSdkVersion safeExtGet('MlkitFaceDetection_minSdkVersion', 16)
        targetSdkVersion safeExtGet('MlkitFaceDetection_targetSdkVersion', 29)
        versionCode 1
        versionName "1.0"

        externalNativeBuild {
            cmake {
                cppFlags "-O2 -frtti -fexceptions -Wall -fstack-protector-all"
                abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a'
              arguments cmakeArgs
            }
        }

    }

    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }

    buildTypes {
        release {
            minifyEnabled false
        }
    }
    lintOptions {
        disable 'GradleCompatible'
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

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

dependencies {
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'com.google.mlkit:face-detection:16.1.3'
    if(hasVisionCamera) {
      implementation "androidx.camera:camera-core:1.1.0-alpha12"
      implementation "androidx.camera:camera-camera2:1.1.0-alpha12"
    }
//    if(hasNativeVideo) {
//      implementation project("react-native-native-video")
//    }
}
