// 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 = 28
def DEFAULT_BUILD_TOOLS_VERSION = '28.0.3'
def DEFAULT_MIN_SDK_VERSION = 18
def DEFAULT_TARGET_SDK_VERSION = 28
def DEFAULT_NDK_VERSION = '21.0.6113669'

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

apply plugin: 'com.android.library'
apply plugin: 'maven'

def jscIncDir = "${buildDir}/JSC/include"
def extractedLibDir = "${buildDir}/lib"

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()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.4.1'
        }
    }
}

apply plugin: 'com.android.library'
apply plugin: 'maven'

configurations { natives }

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=c++_static',
                        '-DENABLE_GLSLANG_BINARIES=OFF',
                        '-DSPIRV_CROSS_CLI=OFF',
                        "-DANDROID_JSC_LIBPATH=${extractedLibDir}/jni",
                        "-DANDROID_JSC_INCPATH=${jscIncDir}",
                        "-DARCORE_LIBPATH=${extractedLibDir}/jni"
            }
        }
        ndk {
            abiFilters "arm64-v8a", "armeabi-v7a", "x86"
        }
    }
    lintOptions {
        abortOnError false
    }
    externalNativeBuild {
        cmake {
            version '3.13.2+'
            path 'CMakeLists.txt'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

repositories {
    // ref: https://www.baeldung.com/maven-local-repository
    mavenLocal()
    maven {
        // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
        url "$rootDir/../node_modules/react-native/android"
    }
    maven {
        // Android JSC is installed from npm
        url "$rootDir/../node_modules/jsc-android/dist"
    }
    google()
    jcenter()
}

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

    natives 'org.webkit:android-jsc:+'
    natives 'com.google.ar:core:1.14.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.reactlibrary"
        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
            }
        }
    }
}

afterEvaluate { project ->
    // some Gradle build hooks ref:
    // https://www.oreilly.com/library/view/gradle-beyond-the/9781449373801/ch03.html
    task androidJavadoc(type: Javadoc) {
        source = android.sourceSets.main.java.srcDirs
        classpath += files(android.bootClasspath)
        classpath += files(project.getConfigurations().getByName('compile').asList())
        include '**/*.java'
    }

    task androidJavadocJar(type: Jar, dependsOn: androidJavadoc) {
        classifier = 'javadoc'
        from androidJavadoc.destinationDir
    }

    task androidSourcesJar(type: Jar) {
        classifier = 'sources'
        from android.sourceSets.main.java.srcDirs
        include '**/*.java'
    }

    android.libraryVariants.all { variant ->
        def name = variant.name.capitalize()
        def javaCompileTask = variant.javaCompileProvider.get()

        task "jar${name}"(type: Jar, dependsOn: javaCompileTask) {
            from javaCompileTask.destinationDir
        }
    }

    artifacts {
        archives androidSourcesJar
        archives androidJavadocJar
    }

    task installArchives(type: Upload) {
        configuration = configurations.archives
        repositories.mavenDeployer {
            // Deploy to react-native-event-bridge/maven, ready to publish to npm
            repository url: "file://${projectDir}/../android/maven"
            configureReactNativePom pom
        }
    }
}

// Extracts the shared libraries from aars in the natives configuration.
// This is done so that NDK builds can access these libraries.
task extractNativeLibraries() {
    // Always extract, this insures the native libs are updated if the version changes.
    outputs.upToDateWhen { false }
    doFirst {
        configurations.natives.files.each { f ->
            copy {
                from zipTree(f)
                into extractedLibDir
                include "jni/**/*"
            }
        }
    }
}

tasks.whenTaskAdded { task ->
    if (task.name.contains("external") && !task.name.contains("Clean")) {
        task.dependsOn(extractNativeLibraries)
    }
}

task copyFiles {
    copy
    {
        from "${rootDir}/../node_modules/jsc-android/dist/include"
        include "*"
        into "${jscIncDir}/JavaScriptCore"
    }
}

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}")
    }
}

preBuild.dependsOn(copyFiles)
