import com.github.triplet.gradle.androidpublisher.ReleaseStatus

apply from: '../spotless.gradle'
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-parcelize'
apply plugin: 'com.github.triplet.play'

def versionMajor = 1
def versionMinor = 15
def versionPatch = 0

def formattedVersionCode = (versionMajor * 10000 + versionMinor * 100 + versionPatch).toString()
def formattedVersionName = "${versionMajor}.${versionMinor}.${versionPatch}"

def DEV_PROPERTIES_FILE = file("../project.properties")
def CI_PROPERTIES_FILE = file("../ci.properties")

def PROPERTY_KEYSTORE_PASSWORD = 'KEYSTORE_PASSWORD'
def PROPERTY_KEYSTORE_ALIAS = 'KEYSTORE_ALIAS'

def DEBUG_KEY_PATH = '../keys/debug.keystore'
def RELEASE_KEY_PATH = '../keys/release.keystore'
def PUBLIC_KEY_PATH = '../keys/public.keystore'
def GOOGLE_CLOUD_KEY_PATH = '../keys/google-cloud-key.json'

def PUBLIC_KEY_PASSWORD = 'abc123'
def PUBLIC_KEY_ALIAS = 'testalias'

project.ext.customProps = new Properties()
if (DEV_PROPERTIES_FILE.exists()) {
    project.ext.customProps.load(new FileInputStream(DEV_PROPERTIES_FILE))
}
if (CI_PROPERTIES_FILE.exists()) {
    project.ext.customProps.load(new FileInputStream(CI_PROPERTIES_FILE))
}

String getCustomProperty(String key) {
    return project.ext.customProps[key] ?: System.getenv(key) ?: ""
}

task generateVersionPropertiesFile {
    // This task is need only for F-Droid
    def PROPERTY_VERSION_CODE = "versionCode"
    def PROPERTY_VERSION_NAME = "versionName"
    def VERSION_PROPERTIES_FILE = file("../version.properties")

    def versions = new Properties()
    if (VERSION_PROPERTIES_FILE.exists()) {
        versions.load(new FileInputStream(VERSION_PROPERTIES_FILE))
    }

    if (versions[PROPERTY_VERSION_CODE] != formattedVersionCode
            || versions[PROPERTY_VERSION_NAME] != formattedVersionName) {
        project.logger.lifecycle("Updating file: version.properties")

        versions.setProperty(PROPERTY_VERSION_CODE, formattedVersionCode)
        versions.setProperty(PROPERTY_VERSION_NAME, formattedVersionName)

        versions.store(new BufferedWriter(new FileWriter(VERSION_PROPERTIES_FILE)),
                "The content of this file is generated automatically for F-Droid")
    }
}

android {
    def ext = rootProject.extensions.ext

    defaultConfig {
        namespace 'com.ivanovsky.passnotes'
        minSdkVersion ext.android.minSdk
        compileSdk ext.android.compileSdk
        targetSdkVersion ext.android.targetSdk
        versionCode formattedVersionCode.toInteger()
        versionName formattedVersionName
        testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
        vectorDrawables.useSupportLibrary true

        project.logger.lifecycle("VersionName: $versionName")
        project.logger.lifecycle("VersionCode: $versionCode")
    }

    buildFeatures {
        compose true
        dataBinding true
        viewBinding true
        buildConfig true
    }

    kapt {
        arguments {
            arg("room.schemaLocation", "$projectDir/schemas")
        }
    }

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

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }

    composeOptions {
        kotlinCompilerExtensionVersion "1.5.14"
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_17.toString()
    }

    signingConfigs {
        debug {
            if (file(DEBUG_KEY_PATH).exists()) {
                storeFile file(DEBUG_KEY_PATH)
            }
        }
        release {
            if (file(RELEASE_KEY_PATH).exists()) {
                storeFile file(RELEASE_KEY_PATH)
                storePassword getCustomProperty(PROPERTY_KEYSTORE_PASSWORD)
                keyAlias getCustomProperty(PROPERTY_KEYSTORE_ALIAS)
                keyPassword getCustomProperty(PROPERTY_KEYSTORE_PASSWORD)
            } else {
                // This signing config is used for CI builds on forked repos
                storeFile file(PUBLIC_KEY_PATH)
                storePassword PUBLIC_KEY_PASSWORD
                keyAlias PUBLIC_KEY_ALIAS
                keyPassword PUBLIC_KEY_PASSWORD
                project.logger.lifecycle('Configure release build with public keystore')
            }
        }
    }

    flavorDimensions "default"
    productFlavors {
        fdroid {
            dimension "default"
        }
        gplay {
            dimension "default"
        }
    }

    buildTypes {
        debug {
            debuggable true
            minifyEnabled false
            versionNameSuffix 'd'
            signingConfig signingConfigs.debug
        }
        automation {
            debuggable true
            minifyEnabled false
            signingConfig signingConfigs.debug
            applicationIdSuffix '.automation'
        }
        release {
            debuggable false
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
    }

    testOptions {
        unitTests {
            includeAndroidResources = true
        }
    }

    lintOptions {
        checkReleaseBuilds true
        abortOnError false
    }

    packagingOptions {
        exclude "plugin.properties"
    }

    preBuild.dependsOn(generateVersionPropertiesFile)
}

play {
    serviceAccountCredentials.set(file(GOOGLE_CLOUD_KEY_PATH))
    track = "internal"
    releaseStatus = ReleaseStatus.DRAFT
    defaultToAppBundles = true
    enabled = true
}

def koinVersion = '3.5.0'
def roomVersion = '2.6.1'
def lifecycleExtensionVersion = '2.2.0'
def lifecycleVersion = '2.7.0'
def appCompatVersion = '1.6.1'
def androidAnnotationVersion = '1.7.0'
def coroutinesVersion = '1.7.3'
def recyclerViewVersion = '1.3.2'
def materialVersion = '1.9.0'
def constrainLayoutVersion = '2.1.4'
def cardViewVersion = '1.0.0'
def coreKtxVersion = '1.10.1'
def activityKtxVersion = '1.7.2'
def preferenceKtxVersion = '1.2.1'
def biometricVersion = '1.2.0-alpha05'
def liveDataKtxVersion = '2.7.0'

def okHttpVersion = '4.12.0'
def apacheCommonsLangVersion = '3.13.0'
def sardineAndroidVersion = '0.8'
def ciceroneVersion = '7.1'
def timberVersion = '5.0.1'
def treessenceVersion = '1.0.5'
def kotpassVersion = '0.10.0'
def treeDiffVersion = '0.4.0'
def treeBuilderVersion = '0.4.0'
def fzf4jVersion = '0.2.1'
// More latest version of jgit produce crash on Samsung
def jgitVersion = '6.2.0.202206071550-r'
def totpKtVersion = 'v1.0.0'
def composeIcons = '1.6.8'

// Test
def jUnitVersion = '4.13.2'
def robolectricVersion = '4.10.3'
def androidXRulesVersion = '1.5.0'
def androidXJunitVersion = '1.1.5'
def mockkVersion = '1.13.8'
def truthVersion = '1.1.5'
def androidXArchVersion = '2.2.0'
def androidXCoreVersion = '1.5.0'

dependencies {
    // Test dependencies
    testImplementation "junit:junit:$jUnitVersion"
    testImplementation "io.mockk:mockk:$mockkVersion"
    testImplementation "com.google.truth:truth:$truthVersion"
    testImplementation "androidx.arch.core:core-testing:$androidXArchVersion"
    testImplementation "androidx.test:core:$androidXCoreVersion"
    testImplementation "org.robolectric:robolectric:$robolectricVersion"

    // Android test dependencies
    androidTestImplementation "androidx.test.ext:junit:$androidXJunitVersion"
    androidTestImplementation "androidx.test:rules:$androidXRulesVersion"
    androidTestImplementation "androidx.room:room-testing:$roomVersion"
    androidTestImplementation "com.google.truth:truth:$truthVersion"
    androidTestImplementation "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion"

    // DI
    implementation "io.insert-koin:koin-android:$koinVersion"
    implementation "io.insert-koin:koin-core:$koinVersion"
//    implementation "io.insert-koin:koin-androidx-viewmodel:$koinVersion"

    // Room
    implementation "androidx.room:room-runtime:$roomVersion"
    kapt "androidx.room:room-compiler:$roomVersion"
    androidTestImplementation "androidx.room:room-testing:$roomVersion"

    // AndroidX libraries
    implementation "androidx.appcompat:appcompat:$appCompatVersion"
    implementation "com.google.android.material:material:$materialVersion"
    implementation "androidx.recyclerview:recyclerview:$recyclerViewVersion"
    implementation "androidx.cardview:cardview:$cardViewVersion"
    implementation "androidx.annotation:annotation:$androidAnnotationVersion"
    implementation "androidx.constraintlayout:constraintlayout:$constrainLayoutVersion"
    implementation "androidx.biometric:biometric:$biometricVersion"
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycleExtensionVersion"
    implementation "androidx.core:core-ktx:$coreKtxVersion"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$liveDataKtxVersion"
    implementation "androidx.activity:activity-ktx:$activityKtxVersion"
    implementation "androidx.preference:preference-ktx:$preferenceKtxVersion"

    // Compose
    implementation platform("androidx.compose:compose-bom:2024.02.00")
    implementation "androidx.compose.material3:material3"
    implementation "androidx.activity:activity-compose"
    implementation "androidx.lifecycle:lifecycle-runtime-compose:$lifecycleVersion"
    implementation "androidx.compose.runtime:runtime-livedata"
    implementation "androidx.compose.material:material-icons-extended:$composeIcons"

    // Compose preview
    implementation "androidx.compose.ui:ui-tooling-preview"
    debugImplementation "androidx.compose.ui:ui-tooling"

    //Apache Commons Lang (TODO: remove)
    implementation "org.apache.commons:commons-lang3:$apacheCommonsLangVersion"

    // Kotlin
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
    implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutinesVersion"

    // OkHttp
    implementation "com.squareup.okhttp3:okhttp:$okHttpVersion"
    implementation "com.squareup.okhttp3:logging-interceptor:$okHttpVersion"

    // WebDAV client
    implementation "com.github.thegrizzlylabs:sardine-android:$sardineAndroidVersion"

    //Cicerone
    implementation "com.github.terrakok:cicerone:$ciceroneVersion"

    // Timber
    implementation "com.jakewharton.timber:timber:$timberVersion"
    implementation "com.github.bastienpaulfr:Treessence:$treessenceVersion"

    // JGit
    implementation "org.eclipse.jgit:org.eclipse.jgit:$jgitVersion"
    implementation "org.eclipse.jgit:org.eclipse.jgit.ssh.jsch:$jgitVersion"

    // KeePass
    implementation "app.keemobile:kotpass:$kotpassVersion"
    implementation "com.github.aivanovski:keepass-tree-diff:$treeDiffVersion"
    implementation "com.github.aivanovski:keepass-tree-builder:$treeBuilderVersion"

    // Fuzzy search
    implementation "com.github.aivanovski:fzf4j:$fzf4jVersion"

    // TOTP + HOTP
    implementation "com.github.robinohs:totp-kt:$totpKtVersion"
}