apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-parcelize'
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'
//apply plugin: 'com.getkeepsafe.dexcount'
apply plugin: 'com.gladed.androidgitversion'


buildscript {
    repositories {
        mavenCentral()
        maven { url "https://plugins.gradle.org/m2/" }
    }
    dependencies {
        classpath "com.github.node-gradle:gradle-node-plugin:${Versions.nodeGradle}"
    }
}

apply plugin: 'com.github.node-gradle.node'

apply from: '../spotless.gradle'
group = APP_GROUP

android {
    compileSdkVersion Versions.targetSdk

    androidGitVersion {
        codeFormat = 'MMNNPPXX'
        format = '%tag%%-count%%-commit%'
        prefix 'v'
    }

    defaultConfig {
        applicationId "${project.APP_GROUP}.${project.APP_ID.toLowerCase(Locale.CANADA)}"
        minSdkVersion kau.Versions.minSdk
        targetSdkVersion Versions.targetSdk
        versionCode 3020000
//        versionCode androidGitVersion.code()
        versionName '3.2.0'
//        versionName androidGitVersion.name()

        if (System.getenv('CI') != 'true') {
            // Verification for F-Droid builds
            if (versionCode != androidGitVersion.code()) {
                throw new GradleException("Version code mismatch, expected ${androidGitVersion.code()}, got $versionCode")
            }
            if (versionName != androidGitVersion.name()) {
                throw new GradleException("Version name mismatch, expected ${androidGitVersion.name()}, got $versionName")
            }
        }
        multiDexEnabled true
        testInstrumentationRunner "com.pitchedapps.frost.FrostTestRunner"
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += ["room.schemaLocation": "$projectDir/src/schemas".toString()]
            }
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.all {
            outputFileName = "${project.APP_ID}-${variant.buildType.name}.apk"
        }
    }

    lintOptions {
        warningsAsErrors false
        disable 'TrustAllX509TrustManager',
                'UnusedResources',
                'ContentDescription',
                'RtlSymmetry',
                'MissingTranslation',
                'TypographyQuotes',
                'DuplicateStrings',
                'UnusedIds',
                'SyntheticAccessor',
                'Recycle',
                'AppLinksAutoVerifyWarning',
                'AppLinksAutoVerifyError',
                'GoogleAppIndexingApiWarning',
                'SelectableText'

        abortOnError true
        xmlReport false
        textReport true
        textOutput 'stdout'
    }

    buildFeatures {
        viewBinding = true
    }

    def testKeystoreFile = file('../files/test.keystore')
    def testPropFile = file('../files/test.properties')
    def withTestSigning = testKeystoreFile.exists() && testPropFile.exists()

    def releaseKeystoreFile = file('../files/release.keystore')
    def releasePropFile = file('../files/release.properties')
    def withReleaseSigning = releaseKeystoreFile.exists() && releasePropFile.exists()

    signingConfigs {

        debug {
            storeFile file("../files/debug.keystore")
            storePassword "debugKey"
            keyAlias "debugKey"
            keyPassword "debugKey"
        }

        if (withTestSigning) {
            def testProps = new Properties()
            testPropFile.withInputStream { testProps.load(it) }

            test {
                storeFile testKeystoreFile
                storePassword testProps.getProperty('storePassword')
                keyAlias testProps.getProperty('keyAlias')
                keyPassword testProps.getProperty('keyPassword')
            }
        }

        if (withReleaseSigning) {
            def releaseProps = new Properties()
            releasePropFile.withInputStream { releaseProps.load(it) }

            release {
                storeFile releaseKeystoreFile
                storePassword releaseProps.getProperty('storePassword')
                keyAlias releaseProps.getProperty('keyAlias')
                keyPassword releaseProps.getProperty('keyPassword')
            }
        }

    }

    def compilerArgs = [
            // "-XXLanguage:+InlineClasses",
            "-Xopt-in=kotlin.RequiresOptIn",
    ]

    buildTypes {
        debug {
            minifyEnabled false
            shrinkResources false
            applicationIdSuffix ".debug"
            versionNameSuffix "-debug"
            signingConfig signingConfigs.debug
            resValue "string", "frost_name", "Frost Debug"
            resValue "string", "frost_web", "Frost Web Debug"

            kotlinOptions.freeCompilerArgs += compilerArgs
        }
        releaseTest {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            applicationIdSuffix ".test"
            versionNameSuffix "-test"
            if (withTestSigning) signingConfig signingConfigs.test
            resValue "string", "frost_name", "Frost Test"
            resValue "string", "frost_web", "Frost Web Test"
        }
        release {
            minifyEnabled true
            shrinkResources true
            if (withReleaseSigning) signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "frost_name", "Frost"
            resValue "string", "frost_web", "Frost Web"
        }
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
        test.java.srcDirs += 'src/test/kotlin'
        androidTest.java.srcDirs += 'src/androidTest/kotlin'
        main.assets.srcDirs += ['src/web/assets']
    }

    packagingOptions {
        pickFirst 'META-INF/core_release.kotlin_module'
        pickFirst 'META-INF/library_release.kotlin_module'
    }

    compileOptions {
        sourceCompatibility kau.Versions.java
        targetCompatibility kau.Versions.java
    }

    kotlinOptions {
        jvmTarget = kau.Versions.java.toString()
    }

    testOptions.unitTests {
        includeAndroidResources = true
        // Don't throw runtime exceptions for android calls that are not mocked
        returnDefaultValues = true

        // Always show the result of every unit test, even if it passes.
        all {
            testLogging {
                events 'skipped', 'failed', 'standardError'
            }
        }
    }

}

node {
    version = '17.0.1'
    npmVersion = '8.19.2'
    download = true
    nodeModulesDir = file("${project.projectDir}/src/web")
}

task npmCi(type: NpmTask) {
    dependsOn npmSetup
    npmCommand = ["ci"]
}

task frostWebGen(type: NpmTask) {
    dependsOn npmCi
    group 'build'
    description 'Generate Frost web assets'
    args = ['run', 'compile']
}

preBuild.dependsOn(frostWebGen)

repositories {
    google()
    // Required for exomedia
    jcenter()
    mavenCentral()
    maven { url "https://jitpack.io" }
}

dependencies {
    androidTestImplementation kau.Dependencies.kotlinTest
    androidTestImplementation kau.Dependencies.espresso
    androidTestImplementation kau.Dependencies.testRules
    androidTestImplementation kau.Dependencies.testRunner
    androidTestImplementation kau.Dependencies.kotlinReflect

    testImplementation kau.Dependencies.kotlinTest
    testImplementation kau.Dependencies.kotlinReflect
    testImplementation kau.Dependencies.junit

    implementation kau.Dependencies.kotlin

    //noinspection GradleDependency
    implementation kau.Dependencies.kau('core', KAU)
    //noinspection GradleDependency
    implementation kau.Dependencies.kau('core-ui', KAU)
    //noinspection GradleDependency
    implementation kau.Dependencies.kau('adapter', KAU)
    //noinspection GradleDependency
    implementation kau.Dependencies.kau('fastadapter', KAU)
    //noinspection GradleDependency
    implementation kau.Dependencies.kau('about', KAU)
    //noinspection GradleDependency
    implementation kau.Dependencies.kau('colorpicker', KAU)
    //noinspection GradleDependency
    implementation kau.Dependencies.kau('mediapicker', KAU)
    //noinspection GradleDependency
    implementation kau.Dependencies.kau('kpref-activity', KAU)
    //noinspection GradleDependency
    implementation kau.Dependencies.kau('searchview', KAU)

    implementation kau.Dependencies.coreKtx
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.5.1"

    implementation kau.Dependencies.swipeRefreshLayout

    implementation "androidx.biometric:biometric:${Versions.andxBiometric}"

    implementation "com.github.piasy:BigImageViewer:${Versions.bigImageViewer}"
    implementation "com.github.piasy:GlideImageLoader:${Versions.bigImageViewer}"
    implementation "com.github.piasy:GlideImageViewFactory:${Versions.bigImageViewer}"

    implementation kau.Dependencies.hilt
    kapt kau.Dependencies.hiltCompiler
    testImplementation kau.Dependencies.hiltTest
    kaptTest kau.Dependencies.hiltCompiler
    androidTestImplementation kau.Dependencies.hiltTest
    kaptAndroidTest kau.Dependencies.hiltCompiler

    implementation kau.Dependencies.coroutines

    implementation "org.apache.commons:commons-text:${Versions.apacheCommonsText}"

    implementation "com.devbrackets.android:exomedia:${Versions.exoMedia}"

    implementation kau.Dependencies.fastAdapter("diff")
    implementation kau.Dependencies.fastAdapter("drag")
    implementation kau.Dependencies.fastAdapter("expandable")

    //noinspection GradleDependency
    implementation kau.Dependencies.glide
    //noinspection GradleDependency
    kapt kau.Dependencies.glideKapt

    debugImplementation kau.Dependencies.leakCanary

    //Icons
    implementation kau.Dependencies.iconics

    implementation kau.Dependencies.iconicsGoogle
    implementation kau.Dependencies.iconicsMaterial
    implementation kau.Dependencies.iconicsCommunity

    implementation kau.Dependencies.materialDialog("input")

    implementation "org.jsoup:jsoup:${Versions.jsoup}"

    implementation "com.squareup.okhttp3:okhttp:${Versions.okhttp}"
    implementation "com.squareup.okhttp3:logging-interceptor:${Versions.okhttp}"
    testImplementation "com.squareup.okhttp3:mockwebserver:${Versions.okhttp}"
    androidTestImplementation "com.squareup.okhttp3:mockwebserver:${Versions.okhttp}"

    implementation "androidx.room:room-ktx:${Versions.room}"
    implementation "androidx.room:room-runtime:${Versions.room}"
    kapt "androidx.room:room-compiler:${Versions.room}"
    androidTestImplementation "androidx.room:room-testing:${Versions.room}"

}

kapt {
    correctErrorTypes true
}

def kotlinResolutions = ['kotlin-reflect',
                         'kotlin-stdlib',
                         'kotlin-stdlib-jdk7',
                         'kotlin-stdlib-jdk8',
                         'kotlin-test',
                         'kotlin-test-junit4',
                         'kotlin-test-junit5']

configurations.all {
    resolutionStrategy {
        eachDependency { DependencyResolveDetails details ->
            def requested = details.requested
            if (requested.group == 'org.jetbrains.kotlin' && requested.name in kotlinResolutions) {
                details.useVersion kau.Versions.kotlin
            }
        }

        dependencySubstitution {
            substitute module('com.mikepenz:library-typeface-api') using module("com.mikepenz:iconics-typeface-api:${kau.Versions.iconics}")
        }
    }
}

task lintGithubReleaseApk {
    dependsOn 'spotlessCheck'
    dependsOn 'lintRelease'
}

task testGithubReleaseApk {
    dependsOn 'testReleaseUnitTest'
    dependsOn 'connectedAndroidTest'
}

task assembleGithubReleaseApk {
    dependsOn 'assembleRelease'
}

// Validates code and generates apk
// TODO order tasks; though technically it doesn't matter
task createGithubReleaseApk {
    dependsOn 'lintGithubReleaseApk'
    dependsOn 'testGithubReleaseApk'
    dependsOn 'assembleGithubReleaseApk'

    tasks.findByName('testGithubReleaseApk').mustRunAfter 'lintGithubReleaseApk'
    tasks.findByName('assembleGithubReleaseApk').mustRunAfter 'testGithubReleaseApk'
}