apply plugin: 'com.android.application'

static <T> T getExtValue(Project proj, String key, T defaultValue) {
    if (proj.hasProperty(key)) {
        return proj.getProperties().get(key)
    } else {
        return defaultValue
    }
}

static String calculateApplicationId(Project proj) {
    String addOnName = proj.parent.name
    String defaultId = "com.anysoftkeyboard."
    if (proj.path.contains('languages')) {
        defaultId += "languagepack.${addOnName}"
    } else if (proj.path.contains('themes')) {
        defaultId += "theme.${addOnName}"
    } else if (proj.path.contains('quicktexts')) {
        defaultId += "quicktexts.${addOnName}"
    } else if (proj.path.contains('ime')) {
        defaultId = 'com.menny.android.anysoftkeyboard'
    } else {
        throw new IllegalStateException('Called on an APK project that has an unknown parent')
    }

    return getExtValue(proj, "override_app_id", defaultId)
}

apply from: "${rootDir}/gradle/android_general.gradle"

//copy bundles and APKs to output
android.applicationVariants.configureEach { variant ->
    def bundleProvider = tasks.named("sign${variant.name.capitalize()}Bundle")
    def bundleCopy = tasks.register("copy${variant.name.capitalize()}Aab", Copy)
    bundleCopy.configure { copier ->
        copier.from "${project.buildDir.absolutePath}/outputs/bundle/${variant.name}/${project.name}-${variant.name}.aab"
        copier.destinationDir file("${rootDir.absolutePath}/outputs/bundle/")
        copier.rename ".*", "${project.parent.name}_${variant.name}.aab"
        copier.dependsOn bundleProvider
    }
    bundleProvider.configure {
        finalizedBy(bundleCopy)
    }

    def assembleProvider = tasks.named("assemble${variant.name.capitalize()}")
    def apkCopy = tasks.register("copy${variant.name.capitalize()}Apk", Copy)
    apkCopy.configure { copier ->
        copier.from "${project.buildDir.absolutePath}/outputs/apk/${variant.name}/${project.name}-${variant.name}.apk"
        copier.destinationDir file("${rootDir.absolutePath}/outputs/apk/")
        copier.rename ".*", "${project.parent.name}_${variant.name}.apk"
        copier.dependsOn assembleProvider
    }
    assembleProvider.configure {
        finalizedBy(apkCopy)
    }
}

group calculateApplicationId(project)

android {
    defaultConfig {
        applicationId calculateApplicationId(project)
    }

    namespace calculateApplicationId(project)

    def keystoreFile = file("/tmp/anysoftkeyboard.keystore")

    signingConfigs {
        release {
            if (keystoreFile.exists()) {
                storeFile keystoreFile
                storePassword System.getenv("KEY_STORE_FILE_PASSWORD")
                keyAlias getExtValue(project, 'override_release_key_alias', 'packs')
                keyPassword System.getenv("KEY_STORE_FILE_DEFAULT_ALIAS_PASSWORD")
                println "Using '${storeFile.absolutePath}' to release APK ${path} (with alias '${keyAlias}')."
            } else {
                println "Could not find '${keystoreFile.absolutePath}' file. Release APK will not be signed."
            }
        }
    }

    buildTypes {
        release {
            if (keystoreFile.exists()) {
                signingConfig signingConfigs.release
            }
            zipAlignEnabled true
            debuggable false
            minifyEnabled false
        }
    }
}

String publishingTrack = rootProject.getProperties().getOrDefault("onlyPublishSupporting", "")
if (project.ext.shouldBePublished && !publishingTrack.isEmpty()) {
    project.apply plugin: 'com.github.triplet.play'

    play {
        serviceAccountCredentials = file('/tmp/apk_upload_key.json')
    }

    // calculating whether we want to enable publishing now
    def supportedTracks = Arrays.asList(
            'production',
            getExtValue(project, 'openTestingTrackName', ''),
            getExtValue(project, 'closedTestingTrackName', '')
    )

    boolean allowPublishing = supportedTracks.stream()
            .filter({ !it.isBlank()})
            .anyMatch({ (it == publishingTrack) });


    tasks.configureEach { newTask ->
            if (newTask.getClass().name.startsWith('com.github.triplet.gradle.play.tasks.Publish')) {
                println("Task ${newTask.path} publish is ${allowPublishing? 'enabled' : 'disabled'} for track-name is ${publishingTrack}.")
                newTask.enabled(allowPublishing)
            }
        }

    //verifying release-notes file
    File playStoreWhatsNewFile = file("${project.projectDir}/src/main/play/release-notes/en-US/alpha.txt")
    if (!playStoreWhatsNewFile.exists()) {
        throw new FileNotFoundException("Can not find whatsnew file for Play-Store upload at ${playStoreWhatsNewFile}!")
    }

    if (playStoreWhatsNewFile.text.length() > 500) {
        println("Locale ${Locale.getDefault()}")
        println("file encoding ${CharsetToolkit.defaultSystemCharset}")
        println("File contents:")
        println("***${playStoreWhatsNewFile.text}***")
        throw new IllegalStateException("whatsnew file can not be longer than 500 characters! Currently ${playStoreWhatsNewFile.text.length()}")
    }
} else {
    // creating fake Play tasks to support CI all tasks checks
    tasks.register("generateReleasePlayResources").configure {
        doLast {
            println("running fake ${it.path}")
        }
    }
    tasks.register("generateCanaryPlayResources").configure {
        doLast {
            println("running fake ${it.path}")
        }
    }
}

apply from: "$rootDir/gradle/versioning_apk.gradle"
