def taskRequests = getGradle().getStartParameter().getTaskRequests().toString().toLowerCase()
def isFoss = taskRequests.contains("foss")

apply plugin: "com.android.application"
apply plugin: 'kotlin-android'
apply plugin: "com.facebook.react"

if (!isFoss) {
    apply plugin: 'com.google.firebase.crashlytics'
    apply plugin: 'com.bugsnag.android.gradle'
}

import com.android.build.OutputFile

/**
 * 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.
 */
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 = ["experimentalPlayDebug", "officialPlayDebug", "experimentalFossDebug", "officialFossDebug"]
    /* 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"]
}


// project.ext.react = [
//     bundleAssetName: "app.bundle",
//     iconFontNames: [ 'custom.ttf' ],
//     enableHermes: true,  // clean and rebuild if changing
// ]

/**
 * Set this to true to create four separate APKs instead of one,
 * one for each native architecture. This is useful if you don't
 * use App Bundles (https://developer.android.com/guide/app-bundle/)
 * and want to have separate APKs to upload to the Play Store.
 */
def enableSeparateBuildPerCPUArchitecture = false

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

/**
 * The preferred build flavor of JavaScriptCore (JSC)
 *
 * 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:+'

/**
 * Private function to get the list of Native Architectures you want to build.
 * This reads the value from reactNativeArchitectures in your gradle.properties
 * file and works together with the --active-arch-only flag of react-native run-android.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

android {
    ndkVersion rootProject.ext.ndkVersion
    compileSdkVersion rootProject.ext.compileSdkVersion

    // Can't set this, since it causes issues to Official flavor
    // namespace APPLICATION_ID 
    defaultConfig {
        applicationId APPLICATION_ID
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode VERSIONCODE as Integer
        versionName "4.40.0"
        vectorDrawables.useSupportLibrary = true
        if (!isFoss) {
            manifestPlaceholders = [BugsnagAPIKey: BugsnagAPIKey as String]
            missingDimensionStrategy "RNNotifications.reactNativeVersion", "reactNative60" // See note below!
        }
        resValue "string", "rn_config_reader_custom_package", "chat.rocket.reactnative"
        testBuildType System.getProperty('testBuildType', 'debug')
        testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
    }

    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include (*reactNativeArchitectures())
        }
    }
    signingConfigs {
        release {
            if (project.hasProperty('KEYSTORE')) {
                storeFile file(KEYSTORE)
                storePassword KEYSTORE_PASSWORD
                keyAlias KEY_ALIAS
                keyPassword KEY_PASSWORD
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            setProguardFiles([getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'])
            proguardFile "${rootProject.projectDir}/../node_modules/detox/android/detox/proguard-rules-app.pro"
            signingConfig signingConfigs.release
            if (!isFoss) {
                firebaseCrashlytics {
                    nativeSymbolUploadEnabled true
                    strippedNativeLibsDir 'build/intermediates/stripped_native_libs/release/out/lib'
                    unstrippedNativeLibsDir 'build/intermediates/merged_native_libs/release/out/lib'
                }
            }
        }
    }

    // applicationVariants are e.g. debug, release

    flavorDimensions "app", "type"
    productFlavors {
        official {
            dimension = "app"
            buildConfigField "boolean", "IS_OFFICIAL", "true"
        }
        experimental {
            dimension = "app"
            buildConfigField "boolean", "IS_OFFICIAL", "false"
        }
        foss {
            dimension = "type"
            buildConfigField "boolean", "FDROID_BUILD", "true"
        }
        play {
            dimension = "type"
            buildConfigField "boolean", "FDROID_BUILD", "false"
        }
    }
    sourceSets {
        // TODO: refactor making sure notifications are working properly both on debug and release
        experimentalPlayDebug {
            java.srcDirs = ['src/main/java', 'src/play/java']
            manifest.srcFile 'src/play/AndroidManifest.xml'
        }
        experimentalPlayRelease {
            java.srcDirs = ['src/main/java', 'src/play/java']
            manifest.srcFile 'src/play/AndroidManifest.xml'
        }
        officialPlayDebug {
            java.srcDirs = ['src/main/java', 'src/play/java']
            manifest.srcFile 'src/play/AndroidManifest.xml'
        }
        officialPlayRelease {
            java.srcDirs = ['src/main/java', 'src/play/java']
            manifest.srcFile 'src/play/AndroidManifest.xml'
        }
    }

    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
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }

    bundle {
        language {
            enableSplit = false
        }
        density {
            enableSplit = true
        }
        abi {
            enableSplit = true
        }
    }
}

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

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}")
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}")
    if (hermesEnabled.toBoolean()) {
        implementation("com.facebook.react:hermes-android")
    } else {
        implementation jscFlavor
    }

    implementation project(':@react-native-community_viewpager')
    implementation "androidx.core:core-splashscreen:1.0.0"
    playImplementation project(':react-native-notifications')

    playImplementation 'com.google.firebase:firebase-core:16.0.0'
    playImplementation project(':@react-native-firebase_app')
    playImplementation project(':@react-native-firebase_analytics')
    playImplementation project(':@react-native-firebase_crashlytics')

    implementation "com.google.code.gson:gson:2.8.9"
    implementation "com.github.bumptech.glide:glide:4.9.0"
    annotationProcessor "com.github.bumptech.glide:compiler:4.9.0"
    implementation "com.tencent:mmkv-static:1.2.10"
    androidTestImplementation('com.wix:detox:+')
    androidTestImplementation 'androidx.test:core:1.4.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.facebook.soloader:soloader:0.10.4'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
if (!isFoss) {
    apply plugin: 'com.google.gms.google-services'
}

bugsnag {
  uploadReactNativeMappings = false
}
