apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"
apply plugin: "com.google.firebase.firebase-perf"
apply plugin: "fullstory"
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"

/**
 * This is the configuration block to customize your React Native Android app.
 * By default you don't need to apply any configuration, just uncomment the lines you need.
 */

/* Fullstory settings */
fullstory {
    org 'o-1WN56P-na1'
    enabledVariants 'all'
    logcatLevel 'debug'
    recordOnStart false
}

react {
    /* Folders */
    //   The root of your project, i.e. where "package.json" lives. Default is '..'
    // root = file("../../")
    //   The folder where the react-native NPM package is. Default is ../../node_modules/react-native
    // reactNativeDir = file("../../node_modules/react-native")
    //   The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen
    // codegenDir = file("../../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("../../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 = ["developmentDebug", "productionDebug"]

    /* 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 = "ram-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/my-custom-hermesc/bin/hermesc"
    //
    //   The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
    // hermesFlags = ["-O", "-output-source-map"]
    //
    /* Autolinking */
    autolinkLibrariesWithApp()
    // Added by install-expo-modules
    entryFile = file(["node", "-e", "require('expo/scripts/resolveAppEntry')", rootDir.getAbsoluteFile().getParentFile().getAbsolutePath(), "android", "absolute"].execute(null, rootDir).text.trim())
    cliFile = file("../../node_modules/rock/dist/src/bin.js")
    bundleCommand = "bundle"
}

project.ext.envConfigFiles = [
    productionDebug: ".env.production",
    productionRelease: ".env.production",
    adhocRelease: ".env.adhoc",
    developmentRelease: ".env",
    developmentDebug: ".env",
    e2eRelease: "tests/e2e/.env.e2e",
    e2edeltaRelease: "tests/e2e/.env.e2edelta"
]

/**
 * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
 */
def enableProguardInReleaseBuilds = true

/**
 * The preferred build flavor of JavaScriptCore (JSC)
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+`
 *
 * 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 = 'io.github.react-native-community:jsc-android:2026004.+'

android {
    androidResources {
      noCompress += ["bundle"]
    }

    ndkVersion rootProject.ext.ndkVersion

    buildToolsVersion rootProject.ext.buildToolsVersion
    compileSdkVersion rootProject.ext.compileSdkVersion

    namespace "com.expensify.chat"
    defaultConfig {
        applicationId "com.expensify.chat"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        multiDexEnabled rootProject.ext.multiDexEnabled
        versionCode 1009022902
        versionName "9.2.29-2"
        // Supported language variants must be declared here to avoid from being removed during the compilation.
        // This also helps us to not include unnecessary language variants in the APK.
        resConfigs "en", "es"
    }

    flavorDimensions "default"
    productFlavors {
        // we need to define a production flavor but since it has default config, we can leave it empty
        production
        e2e {
            // If  are building a version that won't be uploaded to the play store, we don't have to use production keys
            // applies all non-production flavors
            applicationIdSuffix ".e2e"
            signingConfig signingConfigs.debug
            resValue "string", "build_config_package", "com.expensify.chat"
        }
        e2edelta {
            // If  are building a version that won't be uploaded to the play store, we don't have to use production keys
            // applies all non-production flavors
            applicationIdSuffix ".e2edelta"
            signingConfig signingConfigs.debug
            resValue "string", "build_config_package", "com.expensify.chat"
        }
        adhoc {
            applicationIdSuffix ".adhoc"
            signingConfig signingConfigs.debug
            resValue "string", "build_config_package", "com.expensify.chat"
        }
        development {
            applicationIdSuffix ".dev"
            signingConfig signingConfigs.debug
            resValue "string", "build_config_package", "com.expensify.chat"
        }
    }

    signingConfigs {
        release {
            storeFile file(MYAPP_UPLOAD_STORE_FILE)
            storePassword System.getenv('MYAPP_UPLOAD_STORE_PASSWORD')
            keyAlias MYAPP_UPLOAD_KEY_ALIAS
            keyPassword System.getenv('MYAPP_UPLOAD_KEY_PASSWORD')
        }
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            productFlavors.production.signingConfig signingConfigs.release
            shrinkResources enableProguardInReleaseBuilds
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"

            signingConfig null
            // buildTypes take precedence over productFlavors when it comes to the signing configuration,
            // thus we need to manually set the signing config, so that the e2e uses the debug config again.
            // In other words, the signingConfig setting above will be ignored when we build the flavor in release mode.
            productFlavors.all { flavor ->
                // All release builds should be signed with the release config ...
                flavor.signingConfig signingConfigs.release
            }
            // ... except for the e2e flavor, which we maybe want to build locally:
            productFlavors.e2e.signingConfig signingConfigs.debug
            productFlavors.e2edelta.signingConfig signingConfigs.debug
        }
    }

    // since we don't need variants adhocDebug and e2eDebug, we can force gradle to ignore them
    variantFilter { variant ->
        if (variant.name == "adhocDebug" || variant.name == "e2eDebug" || variant.name == "e2edeltaDebug") {
            setIgnore(true)
        }
    }
}

afterEvaluate {
    // As the App is building from source, we need to make sure hermesc is built before the JS bundle is created.
    // Otherwise the release version of the app will fail to build due to missing hermesc.
    if (reactNativeIncludedBuild != null) {
        def hermesCTask = rootProject.ext.reactNativeIncludedBuild.task(":packages:react-native:ReactAndroid:hermes-engine:buildHermesC")
        android.applicationVariants.configureEach { variant ->
            if (variant.buildType.name == "release" || variant.buildType.name == "adhoc") {
                def variantName = variant.name.capitalize()
                def bundleTask = tasks.named("createBundle${variantName}JsAndAssets").getOrNull()

                if (bundleTask != null) {
                    bundleTask.dependsOn(hermesCTask)
                }
            }
        }
    }

    // If we are not building from source, we need to substitute the react-native and react-android dependencies with our patched versions
    if(!patchedArtifactsConfig.buildFromSource) {
        def group = "com.expensify.${patchedArtifactsConfig.packageName}"
        project.rootProject.allprojects { eachProject ->
                eachProject.configurations.all { configuration ->
                    configuration.resolutionStrategy {
                        dependencySubstitution {
                            substitute(module('com.facebook.react:react-native'))
                                .using(module("${group}:react-android:${patchedArtifactsConfig.version}"))
                            substitute(module('com.facebook.react:react-android'))
                                .using(module("${group}:react-android:${patchedArtifactsConfig.version}"))
                        }
                    force "${group}:react-android:${patchedArtifactsConfig.version}"
                }
            }
        }
    }
}

dependencies {
    // The version of react-native is set by the React Native Gradle Plugin
    implementation("com.facebook.react:react-android")

    if (hermesEnabled.toBoolean()) {
        implementation("com.facebook.react:hermes-android")
    } else {
        implementation jscFlavor
    }

    // Firebase libraries (using the Firebase BoM for consistency - see https://firebase.google.com/docs/android/learn-more#bom)
    implementation platform("com.google.firebase:firebase-bom:29.0.3")
    implementation "com.google.firebase:firebase-perf"
    implementation "com.google.firebase:firebase-crashlytics"

    // GIF support
    implementation 'com.facebook.fresco:fresco:2.5.0'
    implementation 'com.facebook.fresco:animated-gif:2.5.0'

    // AndroidX support library
    implementation 'androidx.legacy:legacy-support-core-utils:1.0.0'

    // Multi Dex Support: https://developer.android.com/studio/build/multidex#mdex-gradle
    implementation 'androidx.multidex:multidex:2.0.1'

    // Plaid SDK
    implementation project(':react-native-plaid-link-sdk')

    // Fixes a version conflict between airship and react-native-plaid-link-sdk
    // This may be fixed by a newer version of the plaid SDK (not working as of 10.0.0)
    implementation "androidx.work:work-runtime-ktx:2.8.0"

    // This okhttp3 dependency prevents the app from crashing - See https://github.com/plaid/react-native-plaid-link-sdk/issues/74#issuecomment-648435002
    implementation "com.squareup.okhttp3:okhttp-urlconnection:4.+"

    implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0")
}

apply plugin: 'com.google.gms.google-services'  // Google Play services Gradle plugin
apply plugin: 'com.google.firebase.crashlytics'
