import java.nio.file.Paths
import java.util.function.Consumer

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
}
println("buildDir:" + rootProject.buildDir)
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("Failed to find node_modules/ path!")
}
def nodeModules = findNodeModules(projectDir)
def prebuiltDir = "$buildDir/react-native-0*/jni"
def reactProperties = new Properties()
file("$nodeModules/react-native/ReactAndroid/gradle.properties").withInputStream { reactProperties.load(it) }
def REACT_NATIVE_VERSION_NAME = reactProperties.getProperty("VERSION_NAME")

android {
    compileSdkVersion safeExtGet('XlogJsi_compileSdkVersion', 29)
    defaultConfig {
        minSdkVersion safeExtGet('XlogJsi_minSdkVersion', 16)
        targetSdkVersion safeExtGet('XlogJsi_targetSdkVersion', 29)
        versionCode 1
        versionName "1.0"

        externalNativeBuild {
            cmake {
                cppFlags "-O2 -frtti -fexceptions -Wall -fstack-protector-all"
                abiFilters 'armeabi-v7a', 'arm64-v8a' // xlog does not support x86 and x86_64
                arguments '-DANDROID_STL=c++_shared',
                  "-DNODE_MODULES_DIR=${nodeModules}",
                  "-DBUILD_DIR=${buildDir}"
            }
        }

    }

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

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

    packagingOptions {
        excludes = ["**/libc++_shared.so", "**/libfbjni.so", "**/libreactnativejni.so", "**/libjsi.so", "**/libfb.so", "**/MANIFEST.MF", "**/libmarsxlog.so"]
    }
}

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

configurations {
  cmake_depends
}

dependencies {
    //noinspection GradleDynamicVersion
  implementation "com.facebook.react:react-native:+"  // From node_modules
  api "com.tencent.mars:mars-xlog:1.2.6"
  cmake_depends "com.tencent.mars:mars-xlog:1.2.6"
}

// 作用是build的时候把 mars-xlog 包里面的 so文件拷贝到 src/main/jniLibs 文件夹
task resolveDependencies {
  project.configurations.each { configuration ->
    if ("cmake_depends".equalsIgnoreCase(configuration.name)) {
      def lib = configuration.resolve()[0]
      copy {
        from zipTree(lib)
        into "${project.buildDir}/unzipXlog/"
        include "jni/**/*.so"
      }
      copy {
        from zipTree("${nodeModules}/react-native/android/com/facebook/react/react-native/${REACT_NATIVE_VERSION_NAME}/react-native-${REACT_NATIVE_VERSION_NAME}-release.aar")
        into "${project.buildDir}/unzipReactNative/"
        include "jni/**/*.so"
      }
    }
  }
}
build.dependsOn resolveDependencies
