import java.nio.file.Paths

def resolveModulePath(packageName) {
    def basePath = rootDir.toPath().normalize()

    // Node's module resolution algorithm searches up to the root directory,
    // after which the base path will be null
    while (basePath) {
        def candidatePath = Paths.get(basePath.toString(), 'node_modules', packageName)
        if (candidatePath.toFile().exists()) {
            return candidatePath.toString()
        }

        basePath = basePath.getParent()
    }

    return null
}

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

def getFlagOrDefault(flagName, defaultValue) {
    rootProject.hasProperty(flagName) ? rootProject.properties[flagName] == "true" : defaultValue
}

def getVersionOrDefault(String flagName, String defaultVersion) {
    rootProject.hasProperty(flagName) ? rootProject.properties[flagName] : defaultVersion
}

def isNewArchitectureEnabled() {
    // To opt-in for the New Architecture, you can either:
    // - Set `newArchEnabled` to true inside the `gradle.properties` file
    // - Invoke gradle with `-newArchEnabled=true`
    // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
    return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

configurations {
    compileClasspath
}

buildscript {
    // kotlin version is dictated by rootProject extension or property in gradle.properties
    ext.asyncStorageKtVersion = rootProject.ext.has('kotlinVersion')
            ? rootProject.ext['kotlinVersion']
            : rootProject.hasProperty('AsyncStorage_kotlinVersion')
            ? rootProject.properties['AsyncStorage_kotlinVersion']
            : '1.8.10'

    repositories {
        mavenCentral()
        google()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$asyncStorageKtVersion"
    }
}

// AsyncStorage has default size of 6MB.
// This is a sane limit to protect the user from the app storing too much data in the database.
// This also protects the database from filling up the disk cache and becoming malformed.
// If you really need bigger size, please keep in mind the potential consequences.
long dbSizeInMB = 6L
def newDbSize = rootProject.properties['AsyncStorage_db_size_in_MB']
if (newDbSize != null && newDbSize.isLong()) {
    dbSizeInMB = newDbSize.toLong()
}

// Instead of reusing AsyncTask thread pool, AsyncStorage can use its own executor
def useDedicatedExecutor = getFlagOrDefault('AsyncStorage_dedicatedExecutor', false)

// Use next storage implementation
def useNextStorage = getFlagOrDefault("AsyncStorage_useNextStorage", false)

apply plugin: 'com.android.library'
if (useNextStorage) {
    apply plugin: 'kotlin-android'
    apply plugin: 'kotlin-kapt'
    apply from: './testresults.gradle'
}

if (isNewArchitectureEnabled()) {
    apply plugin: "com.facebook.react"
}

android {
    def agpVersion = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION
    if (agpVersion.tokenize('.')[0].toInteger() >= 7) {
      namespace "com.reactnativecommunity.asyncstorage"
    }
    
    compileSdkVersion safeExtGet('compileSdkVersion', 32)
    // Used to override the NDK path/version by allowing users to customize
    // the NDK path/version from their root project (e.g. for M1 support)
    if (rootProject.hasProperty("ndkPath")) {
        ndkPath rootProject.ext.ndkPath
    }
    if (rootProject.hasProperty("ndkVersion")) {
        ndkVersion rootProject.ext.ndkVersion
    }


    defaultConfig {
        minSdkVersion safeExtGet('minSdkVersion', 23)
        targetSdkVersion safeExtGet('targetSdkVersion', 32)
        buildConfigField "Long", "AsyncStorage_db_size", "${dbSizeInMB}L"
        buildConfigField "boolean", "AsyncStorage_useDedicatedExecutor", "${useDedicatedExecutor}"
        buildConfigField "boolean", "AsyncStorage_useNextStorage", "${useNextStorage}"
    }
    lintOptions {
        abortOnError false
    }

    if (useNextStorage) {
        testOptions {
            unitTests {
                returnDefaultValues = true
                includeAndroidResources = true
            }
        }
    }

    sourceSets.main {
        java {
            if (useNextStorage) {
                srcDirs += 'src/kotlinPackage/java'
            } else {
                srcDirs += 'src/javaPackage/java'
            }

            if (!isNewArchitectureEnabled()) {
                srcDirs += 'src/oldarch/java'
            }
        }
    }
}

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

dependencies {

    if (useNextStorage) {
        def room_version = getVersionOrDefault('AsyncStorage_next_roomVersion', '2.4.3')
        def coroutines_version = "1.6.4"
        def coroutinesTest_version = "1.6.4"
        // if we don't provide explicit dependency on reflection, kotlin plugin
        // would add one automatically, probably a version that is not compatible with
        // used kotlin
        def kotlinReflect_version = project.ext.asyncStorageKtVersion
        def junit_version = "4.13.2"
        def robolectric_version = "4.7.3"
        def truth_version = "1.1.3"
        def androidxtest_version = "1.4.0"
        def androidtest_junit_version = "1.1.3"

        implementation "androidx.room:room-runtime:$room_version"
        implementation "androidx.room:room-ktx:$room_version"
        implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlinReflect_version"

        implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
        kapt "androidx.room:room-compiler:$room_version"

        testImplementation "junit:junit:$junit_version"
        testImplementation "androidx.test:runner:$androidxtest_version"
        testImplementation "androidx.test:rules:$androidxtest_version"
        testImplementation "androidx.test.ext:junit:$androidtest_junit_version"
        testImplementation "org.robolectric:robolectric:$robolectric_version"
        testImplementation "com.google.truth:truth:$truth_version"
        testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesTest_version"
    }

    implementation 'com.facebook.react:react-native:+' // from node_modules
}
