/* groovylint-disable CompileStatic, DuplicateStringLiteral, NoDef, VariableTypeRequired */

import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
    id 'dev.flutter.flutter-gradle-plugin'
}

// Compare two version a.b.c <==> x.y.z
int compareVersions(String v1, String v2) {
    /* groovylint-disable-next-line DuplicateNumberLiteral */
    def zero = 0
    def parts1 = v1.split('\\.')
    def parts2 = v2.split('\\.')
    def length = Math.max(parts1.length, parts2.length)
    for (int i = zero; i < length; i++) {
        def part1 = i < parts1.length ? parts1[i].toInteger() : zero
        def part2 = i < parts2.length ? parts2[i].toInteger() : zero
        if (part1 != part2) {
            return part1 <=> part2
        }
    }
    return zero
}

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

def customCompileSdkVersion = localProperties.getProperty('flutter.compileSdkVersion')
if (customCompileSdkVersion == null) {
    customCompileSdkVersion = Math.max(35, flutter.compileSdkVersion)
} else {
    customCompileSdkVersion = customCompileSdkVersion.toInteger()
}

def customNdkVersion = localProperties.getProperty('flutter.ndkVersion')
if (customNdkVersion == null) {
    customNdkVersion = '27.0.12077973'
    customNdkVersion = compareVersions(customNdkVersion, flutter.ndkVersion) > 0 ? customNdkVersion : flutter.ndkVersion
}

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    // compileSdkVersion flutter.compileSdkVersion
    compileSdkVersion customCompileSdkVersion
    ndkVersion customNdkVersion

    compileOptions {
        // support for the new language APIs
        coreLibraryDesugaringEnabled true
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }

    kotlinOptions {
        jvmTarget = '17'
    }

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

    defaultConfig {
        multiDexEnabled true
        /* groovylint-disable-next-line LineLength */
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId 'io.github.friesi23.mhabit'
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        resourceConfigurations += [
            'en', 'ar', 'cs', 'de', 'es', 'fa', 'fr', 'he', 'it', 'nb-rNO', 'pl', 'pt-rBR',
            'ru', 'tr', 'uk', 'vi', 'zh', 'zh-rTW']
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : file('key.jks')
            storePassword keystoreProperties['storePassword']
        }
    }

    buildTypes {
        release {
            signingConfig keystoreProperties['storeFile'] ? signingConfigs.release : signingConfigs.debug
        }
    }

    // For Flutter multi-platform compatibility, only use one flavor dimension.
    flavorDimensions += 'default'

    productFlavors {
        f_generic {
            dimension 'default'
        }

        f_dev {
            dimension 'default'
            applicationIdSuffix '.dev'
            versionNameSuffix '-dev'
        }
    }

    buildFeatures {
        buildConfig = true
    }

    // Unverifiable encrypted Blob
    // https://github.com/FriesI23/mhabit/issues/205
    dependenciesInfo {
        includeInApk = false
        includeInBundle = false
    }

    namespace 'io.github.friesi23.mhabit'
}

afterEvaluate {
    android.applicationVariants.all { variant ->
        variant.outputs.all { output ->
            def abi = output.getFilter(com.android.build.api.variant.FilterConfiguration.FilterType.ABI.name())
            def flavorName = variant.flavorName
            def buildType = variant.buildType.name
            if (flavorName != 'f_generic') {
                return
            }
            def fileName = abi != null
                ? "app-${abi}-${buildType}.apk"
                : "app-${buildType}.apk"

            //output.outputFileName = fileName

            // This task ensures compatibility when no flavor is specified.
            variant.assembleProvider.get().doLast {
                def src = output.outputFile
                def destDir = file("${project.buildDir}/outputs/flutter-apk")
                def destFile = destDir.toPath().resolve(fileName)
                if (!Files.exists(destDir.toPath())) {
                    Files.createDirectories(destDir.toPath())
                }
                println("Copying $src to $destFile")
                Files.copy(src.toPath(), destFile, StandardCopyOption.REPLACE_EXISTING)

                def sha1 = MessageDigest.getInstance('SHA-1').digest(src.bytes).encodeHex().toString()
                def sha1File = destDir.toPath().resolve("${fileName}.sha1")
                sha1File.toFile().text = "$sha1"
            }
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation 'androidx.window:window:1.2.0'
    implementation 'androidx.window:window-java:1.2.0'
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.1.5'
}
