apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"

apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"

import com.android.build.OutputFile
import groovy.json.JsonSlurper
import org.apache.tools.ant.taskdefs.condition.Os

react {
    /* Folders */
    //   The root of your project, i.e. where "package.json" lives. Default is '..'
    root = file("$rootDir/../")
    //   The folder where the react-native NPM package is. Default is ../node_modules/react-native
    reactNativeDir = file("$rootDir/../../node_modules/react-native")
    //   The folder where the react-native Codegen package is. Default is ../node_modules/react-native-codegen
    codegenDir = file("$rootDir/../../node_modules/react-native-codegen")
    //   The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
    cliFile = file("$rootDir/../../node_modules/react-native/cli.js")
    /* Variants */
    //   The list of variants to that are debuggable. For those we're going to
    //   skip the bundling of the JS bundle and the assets. By default is just 'debug'.
    //   If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
    // debuggableVariants = ["liteDebug", "prodDebug"]
    /* Bundling */
    //   A list containing the node command and its flags. Default is just 'node'.
    // nodeExecutableAndArgs = ["node"]
    //
    //   The command to run when bundling. By default is 'bundle'
    bundleCommand = "webpack-bundle"
    //
    //   The path to the CLI configuration file. Default is empty.
    // bundleConfig = file(../rn-cli.config.js)
    //
    //   The name of the generated asset file containing your JS bundle
    // bundleAssetName = "MyApplication.android.bundle"
    //
    //   The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
    // entryFile = file("../js/MyApplication.android.js")
    //
    //   A list of extra flags to pass to the 'bundle' commands.
    //   See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
    // extraPackagerArgs = []
    /* Hermes Commands */
    //   The hermes compiler command to run. By default it is 'hermesc'
    hermesCommand = "$rootDir/../../node_modules/react-native/sdks/hermesc/%OS-BIN%/hermesc"
    //
    //   The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
    hermesFlags = ["-O", "-output-source-map"]
}

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = true

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = true

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Architectures to build native code for.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

def fdroidBuild() {
    return project.hasProperty("fdroidBuild") && project.fdroidBuild == "true"
}

def getNpmVersion() {
    def inputFile = file("$rootDir/../../package.json")
    def jsonPackage = new JsonSlurper().parseText(inputFile.text)
    print(jsonPackage["version"])
    return jsonPackage["version"]
}

def isBuildingAAB = gradle.startParameter.getTaskNames().any { it.contains("bundleRelease") }

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    ndkVersion rootProject.ext.ndkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
    compileSdk rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    
    namespace "com.streetwriters.notesnook"
    defaultConfig {
        applicationId "com.streetwriters.notesnook"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        multiDexEnabled true
        versionCode 3028
        versionName getNpmVersion()
        testBuildType System.getProperty('testBuildType', 'debug')
        testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
        missingDimensionStrategy "store", "play"
    }

    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include (*reactNativeArchitectures())
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
          release {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
            buildConfigField "boolean", "FDROID_BUILD", "${fdroidBuild()}"
        }
        release {
            if (file("debug.keystore").exists()) {
                signingConfig signingConfigs.release
            }
            minifyEnabled enableProguardInReleaseBuilds
            shrinkResources false
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            proguardFile "${rootProject.projectDir}/../../node_modules/detox/android/detox/proguard-rules-app.pro"
            buildConfigField "boolean", "FDROID_BUILD", "${fdroidBuild()}"
        
        }
    }

     packagingOptions {
      pickFirst 'lib/x86/libc++_shared.so'
      pickFirst 'lib/x86_64/libc++_shared.so'
      pickFirst 'lib/armeabi-v7a/libc++_shared.so'
      pickFirst 'lib/arm64-v8a/libc++_shared.so'
      jniLibs {
            useLegacyPackaging isBuildingAAB == false
    }
  }

    
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                if (fdroidBuild()) {
                    output.versionCodeOverride =
                       defaultConfig.versionCode * 5 + versionCodes.get(abi)
                    println("Fdroid Version code: ${output.versionCodeOverride} for abi ${versionCodes.get(abi)}");
                } else {
                    if (isBuildingAAB) {
                        output.versionCodeOverride = 4 * 1048576 + defaultConfig.versionCode
                        println("AAB version code: ${output.versionCodeOverride}");
                    } else {
                        output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
                        println("Version code: ${output.versionCodeOverride} for abi ${versionCodes.get(abi)}");
                    }
                    
                }
                
            }

        }
    }

}

dependencies {
    // The version of react-native is set by the React Native Gradle Plugin
    implementation("com.facebook.react:react-android")
    implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.0.0")
    implementation("androidx.core:core-splashscreen:1.0.0")
    
    implementation 'androidx.multidex:multidex:2.0.1' 
    implementation 'com.squareup.okhttp3:okhttp:4.9.2'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.9.2'
    implementation 'com.squareup.okhttp3:okhttp-urlconnection:4.9.2'

    androidTestImplementation('com.wix:detox:+')
    implementation 'androidx.appcompat:appcompat:1.1.0'
    
    if (hermesEnabled.toBoolean()) {
        implementation("com.facebook.react:hermes-android")
    } else {
        implementation jscFlavor
    }
    

}  



task deleteFiles(type: Delete) {
  delete './src/main/assets/static'
}

task copyEditorBundle(type: Copy) {
    from '../../../../../packages/editor-mobile/build.bundle'
    into './src/main/assets'
}

task copyPlainEditorBundle(type: Copy) {
    from '../../ios/extension.bundle'
    into './src/main/assets'
}

task copyFontFiles(type: Copy) {
    from '../../fonts'
    into './src/main/assets/fonts'
}


copyEditorBundle.dependsOn(deleteFiles)
copyFontFiles.dependsOn(copyEditorBundle);
copyPlainEditorBundle.dependsOn(copyFontFiles);
preBuild.dependsOn(copyPlainEditorBundle)

apply from: file("../../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)



