// android/build.gradle

// based on:
//
// * https://github.com/facebook/react-native/blob/0.60-stable/template/android/build.gradle
//   original location:
//   - https://github.com/facebook/react-native/blob/0.58-stable/local-cli/templates/HelloWorld/android/build.gradle
//
// * https://github.com/facebook/react-native/blob/0.60-stable/template/android/app/build.gradle
//   original location:
//   - https://github.com/facebook/react-native/blob/0.58-stable/local-cli/templates/HelloWorld/android/app/build.gradle

def DEFAULT_COMPILE_SDK_VERSION = 30
def DEFAULT_BUILD_TOOLS_VERSION = '30.0.2'
def DEFAULT_MIN_SDK_VERSION = 21
def DEFAULT_TARGET_SDK_VERSION = 30
def DEFAULT_NDK_VERSION = '23.1.7779620'

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

apply plugin: 'com.android.library'

def rootBuildDir = "${rootProject.rootDir}/../../../../Build/Android"
def extractedLibDir = "${rootBuildDir}/lib"

def REACT_VERSION = 64
def reactProperties = new Properties()
def propertiesFile = file("$projectDir/../../../react-native/ReactAndroid/gradle.properties")
if ( propertiesFile.isFile() ) {
    def propertiesStream = new FileInputStream(propertiesFile)
    reactProperties.load(propertiesStream)
    REACT_VERSION = reactProperties.getProperty("VERSION_NAME").split("\\.")[1].toInteger()
}

def cpp_distribution = (REACT_VERSION >= 71) ? "c++_shared" : "c++_static";

def basekitBuild = 0
if (project.hasProperty("BASEKIT_BUILD")) {
    basekitBuild = project.getProperty("BASEKIT_BUILD")
}

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.
    // ref: https://docs.gradle.org/current/userguide/tutorial_using_tasks.html#sec:build_script_external_dependencies
    if (project == rootProject) {
        repositories {
            google()
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:7.2.2'
        }
    }
}

def graphics_api = safeExtGet('GRAPHICS_API', "OpenGL")

apply plugin: 'com.android.library'

configurations {
    extractHeaders
    extractLibs
}

android {
    compileSdkVersion safeExtGet('compileSdkVersion', DEFAULT_COMPILE_SDK_VERSION)
    buildToolsVersion safeExtGet('buildToolsVersion', DEFAULT_BUILD_TOOLS_VERSION)
    ndkVersion safeExtGet('ndkVersion', DEFAULT_NDK_VERSION)
    defaultConfig {
        minSdkVersion safeExtGet('minSdkVersion', DEFAULT_MIN_SDK_VERSION)
        targetSdkVersion safeExtGet('targetSdkVersion', DEFAULT_TARGET_SDK_VERSION)
        versionCode 1
        versionName "1.0"
        externalNativeBuild {
            cmake {
                abiFilters 'arm64-v8a', 'armeabi-v7a', 'x86', 'x86_64'
                arguments "-DANDROID_STL=${cpp_distribution}",
                        "-DGRAPHICS_API=${graphics_api}",
                        "-DARCORE_LIBPATH=${extractedLibDir}/core-1.22.0.aar/jni",
                        "-DFBJNI_INCPATH=${extractedLibDir}/fbjni-0.3.0-headers.jar/",
                        "-DFBJNI_LIBPATH=${extractedLibDir}/fbjni-0.3.0.aar/jni",
                        "-DREACTNATIVE_DIR=${rootDir}/../node_modules/react-native/",
                        "-DBASEKIT_BUILD=${basekitBuild}"
            }
        }
        ndk {
            abiFilters "arm64-v8a", "armeabi-v7a", "x86", 'x86_64'
        }
        packagingOptions {
            exclude '**/libfbjni.so'
            exclude '**/libarcore_sdk_c.so'

            // Those are prefab libraries distributed via ReactAndroid
            // Due to a bug in AGP, they fire a warning on console as both the JNI
            // and the prefab .so files gets considered.
            exclude "**/libfabricjni.so"
            exclude "**/libfolly_runtime.so"
            exclude "**/libglog.so"
            exclude "**/libjsi.so"
            exclude "**/libreact_codegen_rncore.so"
            exclude "**/libreact_debug.so"
            exclude "**/libreact_nativemodule_core.so"
            exclude "**/libreact_newarchdefaults.so"
            exclude "**/libreact_render_componentregistry.so"
            exclude "**/libreact_render_core.so"
            exclude "**/libreact_render_debug.so"
            exclude "**/libreact_render_graphics.so"
            exclude "**/libreact_render_imagemanager.so"
            exclude "**/libreact_render_mapbuffer.so"
            exclude "**/librrc_image.so"
            exclude "**/librrc_view.so"
            exclude "**/libruntimeexecutor.so"
            exclude "**/libturbomodulejsijni.so"
            exclude "**/libyoga.so"
        }

    }
    lintOptions {
        abortOnError false
    }
    externalNativeBuild {
        cmake {
            version '3.19.6+'
            path 'CMakeLists.txt'
            buildStagingDirectory "${rootBuildDir}"
        }
    }
    buildFeatures {
        prefab true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

repositories {
    google()
    mavenCentral()
}

dependencies {
    //noinspection GradleDynamicVersion
    implementation 'com.facebook.react:react-native:+'  // From node_modules
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'com.google.ar:core:1.22.0'

    extractHeaders 'com.facebook.fbjni:fbjni:0.3.0:headers'
    extractLibs 'com.facebook.fbjni:fbjni:0.3.0', 'com.google.ar:core:1.22.0'
}

def configureReactNativePom(def pom) {
    def packageJson = new groovy.json.JsonSlurper().parseText(file('../package.json').text)

    pom.project {
        name packageJson.title
        artifactId packageJson.name
        version = packageJson.version
        group = "com.babylonreactnative"
        description packageJson.description
        url packageJson.repository.baseUrl

        licenses {
            license {
                name packageJson.license
                url packageJson.repository.baseUrl + '/blob/master/' + packageJson.licenseFilename
                distribution 'repo'
            }
        }

        developers {
            developer {
                id packageJson.author.username
                name packageJson.author.name
            }
        }
    }
}

configurations.extractHeaders.files.each { file ->
    copy {
        from zipTree(file)
        into "$extractedLibDir/" + file.name
        include "**/*.h"
    }
}

configurations.extractLibs.files.each { file ->
    copy {
        from zipTree(file)
        into "$extractedLibDir/" + file.name
        include "jni/**/*"
    }
}

task validateSdk {
    def minSdkVersion = safeExtGet('minSdkVersion', DEFAULT_MIN_SDK_VERSION)
    if (minSdkVersion < DEFAULT_MIN_SDK_VERSION) {
        throw new GradleException("minSdkVersion must be at least ${DEFAULT_MIN_SDK_VERSION} but is currently ${minSdkVersion}")
    }
}
