/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

apply plugin: 'com.android.application'

if (cordovaConfig.IS_GRADLE_PLUGIN_KOTLIN_ENABLED) {
    apply plugin: 'kotlin-android'

    if(!cdvHelpers.isVersionGreaterThanEqual(cordovaConfig.KOTLIN_VERSION, '1.8.0')) {
        println "Kotlin version < 1.8.0 detected. Applying kotlin-android-extensions plugin."
        apply plugin: 'kotlin-android-extensions'
    }
}

buildscript {
    apply from: '../CordovaLib/cordova.gradle'

    // Checks if the kotlin version format is valid.
    if(cordovaConfig.IS_GRADLE_PLUGIN_KOTLIN_ENABLED) {
        if(!cdvHelpers.isVersionValid(cordovaConfig.KOTLIN_VERSION)) {
            throw new GradleException("The defined Kotlin version (${cordovaConfig.KOTLIN_VERSION}) does not appear to be a valid version.")
        }
    }

    apply from: 'repositories.gradle'
    repositories repos

    dependencies {
        classpath "com.android.tools.build:gradle:${cordovaConfig.AGP_VERSION}"

        if (cordovaConfig.IS_GRADLE_PLUGIN_KOTLIN_ENABLED) {
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${cordovaConfig.KOTLIN_VERSION}"
        }

        if(cordovaConfig.IS_GRADLE_PLUGIN_GOOGLE_SERVICES_ENABLED) {
            // Checks if the kotlin version format is valid.
            if(!cdvHelpers.isVersionValid(cordovaConfig.GRADLE_PLUGIN_GOOGLE_SERVICES_VERSION)) {
                throw new GradleException("The defined Google Services plugin version (${cordovaConfig.GRADLE_PLUGIN_GOOGLE_SERVICES_VERSION}) does not appear to be a valid version.")
            }

            // Create the Google Services classpath and set it.
            String gradlePluginGoogleServicesClassPath = "com.google.gms:google-services:${cordovaConfig.GRADLE_PLUGIN_GOOGLE_SERVICES_VERSION}"
            println "Adding classpath: ${gradlePluginGoogleServicesClassPath}"
            classpath gradlePluginGoogleServicesClassPath
        }
    }
}

// Allow plugins to declare Maven dependencies via build-extras.gradle.
allprojects {
    def hasRepositoriesGradle = file('repositories.gradle').exists()
    if (hasRepositoriesGradle) {
        apply from: 'repositories.gradle'
    } else {
        apply from: "${project.rootDir}/repositories.gradle"
    }

    repositories repos
}

task wrapper(type: Wrapper) {
    gradleVersion = cordovaConfig.GRADLE_VERSION
}

// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.
// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.html
ext {
    apply from: '../CordovaLib/cordova.gradle'

    // Sets the versionCode to the given value.
    if (!project.hasProperty('cdvVersionCode')) {
        cdvVersionCode = null
    }
    // Whether to build architecture-specific APKs.
    if (!project.hasProperty('cdvBuildMultipleApks')) {
        cdvBuildMultipleApks = null
    }
    // Whether to append a 0 "abi digit" to versionCode when only a single APK is build
    if (!project.hasProperty('cdvVersionCodeForceAbiDigit')) {
        cdvVersionCodeForceAbiDigit = null
    }
    // .properties files to use for release signing.
    if (!project.hasProperty('cdvReleaseSigningPropertiesFile')) {
        cdvReleaseSigningPropertiesFile = null
    }
    // .properties files to use for debug signing.
    if (!project.hasProperty('cdvDebugSigningPropertiesFile')) {
        cdvDebugSigningPropertiesFile = null
    }
    // Set by build.js script.
    if (!project.hasProperty('cdvBuildArch')) {
        cdvBuildArch = null
    }

    // Plugin gradle extensions can append to this to have code run at the end.
    cdvPluginPostBuildExtras = []
}

// PLUGIN GRADLE EXTENSIONS START
// PLUGIN GRADLE EXTENSIONS END

def hasBuildExtras1 = file('build-extras.gradle').exists()
if (hasBuildExtras1) {
    apply from: 'build-extras.gradle'
}

def hasBuildExtras2 = file('../build-extras.gradle').exists()
if (hasBuildExtras2) {
    apply from: '../build-extras.gradle'
}

// Apply updates that might come from build-extra.
privateHelpers.applyCordovaConfigCustomization()

// Set property defaults after extension .gradle files.
if (ext.cdvDebugSigningPropertiesFile == null && file('../debug-signing.properties').exists()) {
    ext.cdvDebugSigningPropertiesFile = '../debug-signing.properties'
}
if (ext.cdvReleaseSigningPropertiesFile == null && file('../release-signing.properties').exists()) {
    ext.cdvReleaseSigningPropertiesFile = '../release-signing.properties'
}

// Cast to appropriate types.
ext.cdvBuildMultipleApks = cdvBuildMultipleApks == null ? false : cdvBuildMultipleApks.toBoolean();
ext.cdvVersionCodeForceAbiDigit = cdvVersionCodeForceAbiDigit == null ? false : cdvVersionCodeForceAbiDigit.toBoolean();
ext.cdvVersionCode = cdvVersionCode == null ? null : Integer.parseInt('' + cdvVersionCode)

def computeBuildTargetName(debugBuild) {
    def ret = 'assemble'
    if (cdvBuildMultipleApks && cdvBuildArch) {
        def arch = cdvBuildArch == 'arm' ? 'armv7' : cdvBuildArch
        ret += '' + arch.toUpperCase().charAt(0) + arch.substring(1);
    }
    return ret + (debugBuild ? 'Debug' : 'Release')
}

// Make cdvBuild a task that depends on the debug/arch-sepecific task.
task cdvBuildDebug
cdvBuildDebug.dependsOn {
    return computeBuildTargetName(true)
}

task cdvBuildRelease
cdvBuildRelease.dependsOn {
    return computeBuildTargetName(false)
}

task cdvPrintProps {
    doLast {
        println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)
        println('cdvVersionCode=' + cdvVersionCode)
        println('cdvVersionCodeForceAbiDigit=' + cdvVersionCodeForceAbiDigit)
        println('cdvSdkVersion=' + cdvSdkVersion)
        println('cdvMinSdkVersion=' + cdvMinSdkVersion)
        println('cdvMaxSdkVersion=' + cdvMaxSdkVersion)
        println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)
        println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)
        println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)
        println('cdvBuildArch=' + cdvBuildArch)
        println('computedVersionCode=' + android.defaultConfig.versionCode)
        println('cdvAndroidXAppCompatVersion=' + cdvAndroidXAppCompatVersion)
        println('cdvAndroidXWebKitVersion=' + cdvAndroidXWebKitVersion)
        android.productFlavors.each { flavor ->
            println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)
        }
    }
}

android {
    namespace = cordovaConfig.PACKAGE_NAMESPACE

    buildFeatures {
        buildConfig = true
    }

    defaultConfig {
        versionCode cdvVersionCode ?: new BigInteger("" + privateHelpers.extractIntFromManifest("versionCode"))
        applicationId cordovaConfig.PACKAGE_NAMESPACE

        minSdkVersion cordovaConfig.MIN_SDK_VERSION
        if (cordovaConfig.MAX_SDK_VERSION != null) {
            maxSdkVersion cordovaConfig.MAX_SDK_VERSION
        }
        targetSdkVersion cordovaConfig.SDK_VERSION
        compileSdkVersion cordovaConfig.COMPILE_SDK_VERSION
    }

    lintOptions {
      abortOnError = false
    }

    buildToolsVersion cordovaConfig.BUILD_TOOLS_VERSION

    // This code exists for Crosswalk and other Native APIs.
    // By default, we multiply the existing version code in the
    // Android Manifest by 10 and add a number for each architecture.
    // If you are not using Crosswalk or SQLite, you can
    // ignore this chunk of code, and your version codes will be respected.

    if (Boolean.valueOf(cdvBuildMultipleApks)) {
        flavorDimensions "default"

        productFlavors {
            armeabi {
                versionCode defaultConfig.versionCode*10 + 1
                ndk {
                    abiFilters = ["armeabi"]
                }
            }
            armv7 {
                versionCode defaultConfig.versionCode*10 + 2
                ndk {
                    abiFilters = ["armeabi-v7a"]
                }
            }
            arm64 {
                versionCode defaultConfig.versionCode*10 + 3
                ndk {
                    abiFilters = ["arm64-v8a"]
                }
            }
            x86 {
                versionCode defaultConfig.versionCode*10 + 4
                ndk {
                    abiFilters = ["x86"]
                }
            }
            x86_64 {
                versionCode defaultConfig.versionCode*10 + 5
                ndk {
                    abiFilters = ["x86_64"]
                }
            }
        }
    } else if (Boolean.valueOf(cdvVersionCodeForceAbiDigit)) {
        // This provides compatibility to the default logic for versionCode before cordova-android 5.2.0
        defaultConfig {
            versionCode defaultConfig.versionCode*10
        }
    }

    compileOptions {
        sourceCompatibility JavaLanguageVersion.of(cordovaConfig.JAVA_SOURCE_COMPATIBILITY)
        targetCompatibility JavaLanguageVersion.of(cordovaConfig.JAVA_TARGET_COMPATIBILITY)
    }

    if (cordovaConfig.IS_GRADLE_PLUGIN_KOTLIN_ENABLED) {
        // If KOTLIN_JVM_TARGET is null, fallback to JAVA_TARGET_COMPATIBILITY,
        // as they generally should be equal
        cordovaConfig.KOTLIN_JVM_TARGET = cordovaConfig.KOTLIN_JVM_TARGET ?:
                cordovaConfig.JAVA_TARGET_COMPATIBILITY

        kotlinOptions {
            jvmTarget = JavaLanguageVersion.of(cordovaConfig.KOTLIN_JVM_TARGET)
        }
    }

    if (cdvReleaseSigningPropertiesFile) {
        signingConfigs {
            release {
                // These must be set or Gradle will complain (even if they are overridden).
                keyAlias = ""
                keyPassword = ""
                storeFile = null
                storePassword = ""
            }
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
        addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)
    }

    if (cdvDebugSigningPropertiesFile) {
        addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

/*
 * WARNING: Cordova Lib and platform scripts do management inside of this code here,
 * if you are adding the dependencies manually, do so outside the comments, otherwise
 * the Cordova tools will overwrite them
 */


dependencies {
    implementation fileTree(dir: 'libs', include: '*.jar')
    implementation "androidx.appcompat:appcompat:${cordovaConfig.ANDROIDX_APP_COMPAT_VERSION}"
    implementation "androidx.core:core-splashscreen:${cordovaConfig.ANDROIDX_CORE_SPLASHSCREEN_VERSION}"

    if (cordovaConfig.IS_GRADLE_PLUGIN_KOTLIN_ENABLED) {
        implementation "org.jetbrains.kotlin:kotlin-stdlib:${cordovaConfig.KOTLIN_VERSION}"
    }

    constraints {
        implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:${cordovaConfig.KOTLIN_VERSION}") {
            because("kotlin-stdlib-jdk7 is now a part of kotlin-stdlib")
        }
        implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${cordovaConfig.KOTLIN_VERSION}") {
            because("kotlin-stdlib-jdk8 is now a part of kotlin-stdlib")
        }
    }

    // SUB-PROJECT DEPENDENCIES START
    debugCompile(project(path: ":CordovaLib", configuration: "debug"))
    releaseCompile(project(path: ":CordovaLib", configuration: "release"))
    // SUB-PROJECT DEPENDENCIES END
}

def addSigningProps(propsFilePath, signingConfig) {
    def propsFile = file(propsFilePath)
    def props = new Properties()
    propsFile.withReader { reader ->
        props.load(reader)
    }

    def storeFile = new File(props.get('key.store') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'storeFile'))
    if (!storeFile.isAbsolute()) {
        storeFile = RelativePath.parse(true, storeFile.toString()).getFile(propsFile.getParentFile())
    }
    if (!storeFile.exists()) {
        throw new FileNotFoundException('Keystore file does not exist: ' + storeFile.getAbsolutePath())
    }
    signingConfig.keyAlias = props.get('key.alias') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'keyAlias')
    signingConfig.keyPassword = props.get('keyPassword', props.get('key.alias.password', signingConfig.keyPassword))
    signingConfig.storeFile = storeFile
    signingConfig.storePassword = props.get('storePassword', props.get('key.store.password', signingConfig.storePassword))
    def storeType = props.get('storeType', props.get('key.store.type', ''))
    if (!storeType) {
        def filename = storeFile.getName().toLowerCase()
        if (filename.endsWith('.p12') || filename.endsWith('.pfx')) {
            storeType = 'pkcs12'
        } else {
            storeType = signingConfig.storeType // "jks"
        }
    }
    signingConfig.storeType = storeType
}

for (def func : cdvPluginPostBuildExtras) {
    func()
}

// This can be defined within build-extras.gradle as:
//     ext.postBuildExtras = { ... code here ... }
if (hasProperty('postBuildExtras')) {
    postBuildExtras()
}

if (cordovaConfig.IS_GRADLE_PLUGIN_GOOGLE_SERVICES_ENABLED) {
    apply plugin: 'com.google.gms.google-services'
}
