plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}
def getCommitVersionCode = { ->
    try {
        def stdout = new ByteArrayOutputStream()
        exec {
            commandLine 'git', 'rev-list', 'HEAD', '--count'
            standardOutput = stdout
        }
        return Integer.valueOf(stdout.toString().trim())
    } catch (ignored) {
        return null
    }
}

android {
    compileSdk 33
    defaultConfig {
        applicationId "eu.toldi.infinityforlemmy"
        minSdk 21
        targetSdk 33
        versionCode 131
        versionName "0.1.2"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [eventBusIndex: 'eu.toldi.infinityforlemmy.EventBusIndex']
            }
        }
    }
    buildTypes {

        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        minifiedRelease {
            initWith buildTypes.release
            zipAlignEnabled true
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        debug {
            applicationIdSuffix '.debug'
            versionNameSuffix ' (DEBUG)'
        }

        nightly {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            applicationIdSuffix '.nightly'
            versionNameSuffix ' (NIGHTLY)'
        }
        applicationVariants.all { variant ->
            variant.resValue "string", "applicationId", variant.applicationId


            if (variant.buildType.name == 'nightly') {
                variant.outputs.all {
                    setVersionCodeOverride(getCommitVersionCode())

                    setVersionNameOverride(variant.versionName)
                    outputFileName = "${applicationId}.apk"
                }
            }
        }

    }

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

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

    lint {
        disable 'MissingTranslation'
    }

    bundle {
        language {
            enableSplit = false
        }
    }

    buildFeatures {
        viewBinding true
    }

    packagingOptions {
        doNotStrip '**/*.so'
    }

    // Kotlin jvm target
    kotlinOptions {
        jvmTarget = '11'
    }

    namespace 'eu.toldi.infinityforlemmy'


    task rearrangeClass(type: Exec) {
        commandLine 'python3', '../scripts/fixEventBus.py'
    }

    applicationVariants.all { variant ->
        if (variant.name == 'release') {
            task("compileSingleFile${variant.name.capitalize()}", type: JavaCompile, dependsOn: rearrangeClass) {
                def filePath = project.rootDir.absolutePath + '/app/build/generated/ap_generated_sources/release/out/eu/toldi/infinityforlemmy/'
                source = files(filePath)
                includes = ["**/EventBusIndex.java"]
                classpath = variant.getCompileClasspath() + files(project.rootDir.absolutePath + '/app/build/intermediates/javac/release/classes')
                destinationDir = file("$buildDir/intermediates/javac/release/classes")
            }

            tasks.withType(JavaCompile).all { task ->
                if (task.name == 'compileReleaseJavaWithJavac') {
                    task.finalizedBy "compileSingleFile${variant.name.capitalize()}"
                }
            }
        }
    }

}

dependencies {
/** AndroidX **/
    implementation 'androidx.appcompat:appcompat:1.7.0-alpha01'
    implementation 'androidx.biometric:biometric:1.2.0-alpha05'
    implementation 'androidx.browser:browser:1.4.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    def lifecycleVersion = "2.5.1"
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycleVersion"
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycleVersion"
    implementation "androidx.lifecycle:lifecycle-process:$lifecycleVersion"
    implementation "androidx.lifecycle:lifecycle-runtime:$lifecycleVersion"
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycleVersion"

    def pagingVersion = '3.2.0-alpha03'
    implementation "androidx.paging:paging-runtime:$pagingVersion"
    implementation "androidx.paging:paging-guava:$pagingVersion"
    implementation 'androidx.preference:preference:1.2.0'
    implementation 'androidx.recyclerview:recyclerview:1.2.1'
    def roomVersion = "2.4.3"
    implementation "androidx.room:room-runtime:$roomVersion"
    annotationProcessor "androidx.room:room-compiler:$roomVersion"
    implementation "androidx.room:room-guava:$roomVersion"
    implementation 'androidx.viewpager2:viewpager2:1.1.0-beta01'
    implementation 'androidx.work:work-runtime:2.7.1'
    implementation 'com.google.android.material:material:1.8.0'

/** ExoPlayer **/
    def exoplayerVersion = "2.18.2"
    implementation "com.google.android.exoplayer:exoplayer-core:$exoplayerVersion"
    implementation "com.google.android.exoplayer:exoplayer-dash:$exoplayerVersion"
    implementation "com.google.android.exoplayer:exoplayer-hls:$exoplayerVersion"
    implementation "com.google.android.exoplayer:exoplayer-ui:$exoplayerVersion"
    implementation "com.google.android.exoplayer:exoplayer-smoothstreaming:$exoplayerVersion"

/** Third-party **/

/**** Backend logic ****/

    // HTTP clients
    def retrofitVersion = "2.9.0"
    implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
    implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion"
    implementation "com.squareup.retrofit2:adapter-guava:$retrofitVersion"
    implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion"
    implementation 'com.squareup.okhttp3:okhttp:4.9.1'

    // Dependency injection
    def daggerVersion = '2.40.5'
    implementation "com.google.dagger:dagger:$daggerVersion"
    annotationProcessor "com.google.dagger:dagger-compiler:$daggerVersion"


    // Binding
    // NOTE: Deprecated in favor of viewbinding
    def butterknifeVersion = "10.2.3"
    implementation "com.jakewharton:butterknife:$butterknifeVersion"
    annotationProcessor "com.jakewharton:butterknife-compiler:$butterknifeVersion"
    compileOnly 'com.android.databinding:viewbinding:7.3.1'

    // Events
    def eventbusVersion = "3.3.1"
    implementation "org.greenrobot:eventbus:$eventbusVersion"
    annotationProcessor "org.greenrobot:eventbus-annotation-processor:$eventbusVersion"

    // TransactionTooLargeException avoidance
    implementation 'com.github.livefront:bridge:v2.0.2'

    // Bundle-saving without boilerplate
    // NOTE: Deprecated
    def stateVersion = "1.4.1"
    implementation "com.evernote:android-state:$stateVersion"
    annotationProcessor "com.evernote:android-state-processor:$stateVersion"

    // Object to JSON
    // NOTE: Replace with Squareup's Moshi?
    implementation 'com.google.code.gson:gson:2.8.9'

    // Java library for zip files and streams
    implementation 'net.lingala.zip4j:zip4j:2.11.2'

    // IO functionality
    implementation 'commons-io:commons-io:2.5'

    // Crash reporting
    implementation 'com.github.FunkyMuse:Crashy:1.2.0'


/**** User Interface (frontend) ****/

    //Image loading
    def glideVersion = "4.12.0"
    implementation "com.github.bumptech.glide:glide:$glideVersion"
    annotationProcessor "com.github.bumptech.glide:compiler:$glideVersion"
    implementation "com.github.bumptech.glide:okhttp-integration:$glideVersion"
    implementation 'jp.wasabeef:glide-transformations:4.3.0'
    implementation 'com.github.santalu:aspect-ratio-imageview:1.0.9'
    implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.23'
    def bivVersion = "1.8.1"
    implementation "com.github.piasy:BigImageViewer:$bivVersion"
    implementation "com.github.piasy:GlideImageLoader:$bivVersion"
    implementation "com.github.piasy:GlideImageViewFactory:$bivVersion"

    // Markdown
    def markwonVersion = "4.6.2"
    implementation "io.noties.markwon:core:$markwonVersion"
    implementation "io.noties.markwon:ext-strikethrough:$markwonVersion"
    implementation "io.noties.markwon:linkify:$markwonVersion"
    implementation "io.noties.markwon:recycler-table:$markwonVersion"
    implementation "io.noties.markwon:simple-ext:$markwonVersion"
    implementation "io.noties.markwon:inline-parser:$markwonVersion"
    implementation "io.noties.markwon:image-glide:$markwonVersion"
    implementation 'com.atlassian.commonmark:commonmark-ext-gfm-tables:0.14.0'
    implementation 'me.saket:better-link-movement-method:2.2.0'

    // Animations
    implementation 'com.airbnb.android:lottie:4.2.2'

    // Loading ProgressBar
    implementation 'com.lsjwzh:materialloadingprogressbar:0.5.8-RELEASE'

    // Customizable TextView
    implementation 'com.libRG:customtextview:2.4'

    // Dismiss gesturing
    implementation 'app.futured.hauler:hauler:5.0.0'

    // Bottom sheet with rounded corners
    implementation 'com.github.Deishelon:RoundedBottomSheet:1.0.1'

    // FlowLayout (auto-spacing)
    implementation 'com.nex3z:flow-layout:1.3.3'

    // RecyclerView fast scrolling
    implementation 'me.zhanghai.android.fastscroll:library:1.1.8'

    implementation 'com.otaliastudios:zoomlayout:1.9.0'

    implementation 'androidx.core:core-splashscreen:1.0.1'


/**** Builds and flavors ****/
    // debugImplementation because LeakCanary should only run in debug builds.
    //debugImplementation 'com.squareup.leakcanary:leakcanary-android:x.y'
}

// NB: Android Studio can't find the imports; this does not affect the
// actual build since Gradle can find them just fine.

import com.android.tools.profgen.ArtProfileKt
import com.android.tools.profgen.ArtProfileSerializer
import com.android.tools.profgen.DexFile

project.afterEvaluate {
    tasks.each { task ->
        if (task.name.startsWith("compile") && task.name.endsWith("ReleaseArtProfile")) {
            task.doLast {
                outputs.files.each { file ->
                    if (file.name.endsWith(".profm")) {
                        println("Sorting ${file} ...")
                        def version = ArtProfileSerializer.valueOf("METADATA_0_0_2")
                        def profile = ArtProfileKt.ArtProfile(file)
                        def keys = new ArrayList(profile.profileData.keySet())
                        def sortedData = new LinkedHashMap()
                        Collections.sort keys, new DexFile.Companion()
                        keys.each { key -> sortedData[key] = profile.profileData[key] }
                        new FileOutputStream(file).with {
                            write(version.magicBytes$profgen)
                            write(version.versionBytes$profgen)
                            version.write$profgen(it, sortedData, "")
                        }
                    }
                }
            }
        }
    }
}