plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

def taskName = getGradle().getStartParameter().getTaskRequests().toString()


ext {
    FDroidCodeNumber = 6294
    FDroidVersionNumber = "9.0.5"
}


println " --------------------"
println " taskName: " + taskName
println " --------------------"

ext {
    if (!taskName.contains("Fdroid")) {
        codeNumber = Integer.parseInt(appCodeNumber)
        versionNumber = appVersionNumberBase + "." + appVersionNumberIndex
    } else {
        codeNumber = FDroidCodeNumber
        versionNumber = FDroidVersionNumber
    }

    println ""
    println "Version: [" + versionNumber + " - " + codeNumber + "]"
}

android {
    compileSdk = project.compileSdk
    namespace = "com.foobnix.pdf.info"

    defaultConfig {
        namespace = "com.foobnix.pdf.info"
        minSdk = project.minSdk
        targetSdk = project.targetSdk
        versionCode = codeNumber
        versionName = versionNumber
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled = true
    }

    configurations {
        all {
            exclude module: 'httpclient'
            exclude module: 'commons-logging'
        }
    }

    lint {
        abortOnError = true
        ignoreWarnings = true
        checkReleaseBuilds = taskName.contains("Pro")
    }

    testOptions {
        unitTests {
            includeAndroidResources = true
            returnDefaultValues = true
        }
    }

    signingConfigs {
        release {
            storeFile file(RELEASE_STORE_FILE)
            storePassword RELEASE_STORE_PASSWORD
            keyAlias RELEASE_KEY_ALIAS
            keyPassword RELEASE_KEY_PASSWORD
        }
    }

    buildTypes {
        release {
            minifyEnabled = false
            signingConfig = signingConfigs.release
            debuggable = false
        }
        debug {
            debuggable = true
        }
    }
    buildFeatures {
        compose true
    }


    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }

    tasks.withType(JavaCompile) {
        options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
    }

    //compileOptions {
    //coreLibraryDesugaringEnabled true

    //sourceCompatibility JavaVersion.VERSION_1_8
    //targetCompatibility JavaVersion.VERSION_1_8
    //}

    splits {
        abi {
            enable = true
            reset()
            include "x86", "x86_64", "armeabi-v7a", "arm64-v8a"
            universalApk = true
        }
    }

    flavorDimensions.add("version")
    productFlavors {
        fdroid {
            minSdk = project.minFDroidSdk
            dimension = "version"
            applicationId = "com.foobnix.pro.pdf.reader"
            manifestPlaceholders = [
                    appName      : "Librera FD",
                    appIcon      : "@mipmap/icon_pdf_pro",
                    appRoundIcon : "@mipmap/icon_pdf_pro",
                    appGdriveKey : "",
                    admobAppId   : "",
                    admobBannerId: "",
                    admobFullId  : "",
                    appSafeMode  : "true"
            ]
            versionNameSuffix = '-fdroid'
        }
        librera {
            dimension = "version"
            applicationId = "com.foobnix.pdf.reader"
            manifestPlaceholders = [
                    appName      : "Librera",
                    appIcon      : "@mipmap/icon_pdf_reader",
                    appRoundIcon : "@mipmap/icon_pdf_reader",
                    appGdriveKey : librera_appGdriveKey,
                    admobAppId   : librera_admobAppId,
                    admobBannerId: librera_admobBannerId,
                    admobFullId  : librera_admobFullId,
                    appSafeMode  : "false"
            ]
        }

        pro {
            dimension = "version"
            applicationId = "com.foobnix.pro.pdf.reader"
            manifestPlaceholders = [
                    appName      : "Librera",
                    appIcon      : "@mipmap/icon_pdf_pro",
                    appRoundIcon : "@mipmap/icon_pdf_pro",
                    appGdriveKey : pro_appGdriveKey,
                    admobAppId   : "",
                    admobBannerId: "",
                    admobFullId  : "",
                    appSafeMode  : "false"
            ]
        }
        pdf_classic {
            dimension = "version"
            applicationId = "classic.pdf.reader.viewer.djvu.epub.fb2.txt.mobi.book.reader.lirbi.libri"
            manifestPlaceholders = [
                    appName      : "PDF Reader",
                    appIcon      : "@mipmap/icon_pdf_classic",
                    appRoundIcon : "@mipmap/launcher_classic",
                    appGdriveKey : pdf_classic_appGdriveKey,
                    admobAppId   : pdf_classic_admobAppId,
                    admobBannerId: pdf_classic_admobBannerId,
                    admobFullId  : pdf_classic_admobFullId,
                    appSafeMode  : "true"
            ]
        }
        ebooka {
            dimension = "version"
            applicationId = "droid.reader.book.epub.mobi.pdf.djvu.fb2.txt.azw.azw3"
            manifestPlaceholders = [
                    appName      : "Book Reader",
                    appIcon      : "@mipmap/icon_pdf_droid",
                    appRoundIcon : "@mipmap/launcher_droid",
                    appGdriveKey : ebooka_appGdriveKey,
                    admobAppId   : ebooka_admobAppId,
                    admobBannerId: ebooka_admobBannerId,
                    admobFullId  : ebooka_admobFullId,
                    appSafeMode  : "false"
            ]
        }
        pdf_v2 {
            dimension = "version"
            applicationId = "pdf.pdf.reader"
            manifestPlaceholders = [
                    appName      : "PDF Reader",
                    appIcon      : "@mipmap/icon_pdf_2",
                    appRoundIcon : "@mipmap/launcher_pdf_v2",
                    appGdriveKey : pdf_v2_appGdriveKey,
                    admobAppId   : pdf_v2_admobAppId,
                    admobBannerId: pdf_v2_admobBannerId,
                    admobFullId  : pdf_v2_admobFullId,
                    appSafeMode  : "false"
            ]
        }
        tts_reader {
            dimension = "version"
            applicationId = "tts.reader"
            manifestPlaceholders = [
                    appName      : "TTS Reader",
                    appIcon      : "@mipmap/icon_tts_reader_app",
                    appRoundIcon : "@mipmap/launcher_tts_reader_app",
                    appGdriveKey : tts_reader_appGdriveKey,
                    admobAppId   : tts_reader_admobAppId,
                    admobBannerId: tts_reader_admobBannerId,
                    admobFullId  : tts_reader_admobFullId,
                    appSafeMode  : "false"
            ]
        }
        epub_reader {
            dimension = "version"
            applicationId = "epub.reader"
            manifestPlaceholders = [
                    appName      : "Epub Reader",
                    appIcon      : "@mipmap/icon_epub_reader",
                    appRoundIcon : "@mipmap/launcher_epub_reader",
                    appGdriveKey : epub_reader_appGdriveKey,
                    admobAppId   : epub_reader_admobAppId,
                    admobBannerId: epub_reader_admobBannerId,
                    admobFullId  : epub_reader_admobFullId,
                    appSafeMode  : "false"
            ]
        }
    }

    def abiCodes = ['armeabi-v7a': 0, 'arm64-v8a': 1, 'x86': 2, 'x86_64': 3]

    applicationVariants.all { variant ->

        variant.outputs.all { output ->

            def flavor = variant.productFlavors[0].name.capitalize()
            def abiName = getFilter("ABI")
/*            if (abiName == "armeabi-v7a") {
                variant.mergedFlavor.manifestPlaceholders.appSafeMode = "true"
                //variant.resValue "string", "[appSafeMode]", "true"
                println abiName + " : appSafeMode true "
            } else {
                variant.mergedFlavor.manifestPlaceholders.appSafeMode = "true"
                //variant.resValue "string", "[appSafeMode]", "false"
                println abiName + " : appSafeMode false"
            }
*/
            if (abiName != null) {
                def code = abiCodes.get(abiName, 0) + variant.versionCode
                abiName = abiName.replace("arm64-v8a", "arm64").replace("armeabi-v7a", "arm")

                output.versionCodeOverride = code
                //def fullName = "Librera ${flavor}-${versionNumber}-c${code}-d${db}-${abiName}.apk"

                def fullName = "Librera ${flavor}-${versionNumber}-${abiName}.apk"

                output.outputFileName = fullName
            } else {
                //def fullName = "Librera ${flavor}-${versionNumber}-c${codeNumber}-d${db}-universal.apk"
                //def fullName = "Librera ${flavor}-${versionNumber}-universal.apk"
                def fullName = "Librera ${flavor}-${versionNumber}-uni.apk"
                output.versionCodeOverride = codeNumber
                output.outputFileName = fullName
            }
        }
    }

    sourceSets {
        fdroid { assets.srcDirs = ['src/fdroid/assets', 'src/fdroid/assets/'] }
    }

    packagingOptions {
        resources {
            excludes.addAll(
                    'META-INF/DEPENDENCIES',
                    'META-INF/NOTICE',
                    'META-INF/LICENSE',
                    'META-INF/LICENSE.txt',
                    'META-INF/NOTICE.txt',
            )
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    proImplementation project(':libPro')
    fdroidImplementation project(':libPro')
    implementation project(':libReflow')

    //compose

    //implementation project(':appLibDrive')


/** AndroidX **/
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'androidx.recyclerview:recyclerview:1.3.2'
    implementation 'androidx.work:work-runtime:2.10.2'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.appcompat:appcompat:1.7.1'

/** Third-party **/
    //implementation 'com.github.axet:lame:1.0.9'

    implementation 'org.greenrobot:eventbus:3.3.1'
    implementation('org.greenrobot:greendao:3.3.0') {
        exclude group: 'org.greenrobot.greendao.rx'
    }
    implementation 'org.greenrobot:greendao-api:3.3.0'
    implementation 'org.jsoup:jsoup:1.21.1'

    implementation 'com.github.albfernandez:juniversalchardet:2.5.0'

    implementation 'com.squareup.okhttp3:okhttp:3.12.6'
    implementation 'io.github.rburgst:okhttp-digest:1.21'
    implementation 'com.squareup.okio:okio-parent:1.17.6'

    implementation 'com.github.joniles:rtfparserkit:1.16.0'

    implementation 'org.zwobble.mammoth:mammoth:1.5.0'
    implementation 'javax.xml.stream:stax-api:1.0-2'

    implementation 'net.lingala.zip4j:zip4j:2.11.5'
    implementation 'com.github.bumptech.glide:glide:4.16.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0'

    //implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'
    //conflict with worker

    implementation "commons-logging:commons-logging-api:1.1"


    implementation 'androidx.work:work-runtime:2.10.2'
    implementation 'com.google.guava:guava:33.4.8-android'

    //implementation "it.unimi.dsi:fastutil-core:8.5.12"

    //implementation "androidx.car.app:app:1.4.0-rc01"
    //implementation("androidx.media3:media3-ui:1.1.1")

    //implementation('androidx.media3:media3-session:1.3.0')


    //implementation "org.nanohttpd:nanohttpd:2.3.1"


/** Ads **/
    def google_ads = "com.google.android.gms:play-services-ads:24.4.0"
    libreraImplementation google_ads
    pdf_v2Implementation google_ads
    ebookaImplementation google_ads
    tts_readerImplementation google_ads
    pdf_classicImplementation google_ads
    epub_readerImplementation google_ads

    def messaging_ads = "com.google.android.ump:user-messaging-platform:3.2.0"
    libreraImplementation messaging_ads
    pdf_v2Implementation messaging_ads
    ebookaImplementation messaging_ads
    tts_readerImplementation messaging_ads
    pdf_classicImplementation messaging_ads
    epub_readerImplementation messaging_ads


/** Testing **/
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test:runner:1.6.2'
    //androidTestImplementation 'androidx.test:core:1.5.2'
    //androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}


task copyApks() {
    if (project.hasProperty('beta') || project.hasProperty("release")) {
        println "My Task: [copy apks]"

        //delete fileTree("/home/dev/Dropbox/FREE_PDF_APK/testing").include("*.apk")
        //delete fileTree("/home/dev/Nextcloud/LibreraBeta").include("*.apk")
        delete fileTree("/Users/ivanivanenko/Library/CloudStorage/Dropbox/FREE_PDF_APK/testing").include("*.apk")

        delete fileTree("/Users/ivanivanenko/Library/CloudStorage/Dropbox/FREE_PDF_APK/$versionNumber").include("*.apk")
        //delete fileTree("/home/dev/Dropbox/FREE_PDF_APK/testing/$versionNumber").include("*.apk")

        android.applicationVariants.all { variant ->
            if ("release" == variant.buildType.name) {
                def flavor = variant.productFlavors[0].name

                //println "====  " + variant.buildType.name + " " +  flavor

                def list = []

                if (project.hasProperty("beta")) {
                    //list.add("/home/dev/Nextcloud/LibreraBeta")
                    list.add("/Users/ivanivanenko/Library/CloudStorage/Dropbox/FREE_PDF_APK/testing")
                    //list.add("/home/dev/Dropbox/FREE_PDF_APK/testing")
                }


                if (project.hasProperty("release")) {
                    //list.add("/home/dev/Dropbox/FREE_PDF_APK/testing/$versionNumber")
                    list.add("/Users/ivanivanenko/Library/CloudStorage/Dropbox/FREE_PDF_APK/testing/$versionNumber")
                }
                list.each { dest ->

                    copy {
                        from file(
                                "build/outputs/apk/${flavor}/release/"
                        )
                        include "*.apk"
                        into file(dest)
                        println "Copy: '" + flavor + "' to " + dest

                        eachFile {
                            project.file(dest).mkdirs()
                            if (!file(dest).exists()) {
                                it.exclude()
                            }
                        }

                    }


                }
            }
        }

        //File file = new File('/home/data/Dropbox/FREE_PDF_APK/testing/version.txt')
        //file.write versionNumber
    }
}


task incVersion() {
    doLast {
        Properties props = new Properties()
        File progejectDir = layout.projectDirectory.getAsFile()
        println "progejectDir :" + progejectDir

        File propsFile = new File(progejectDir, 'gradle.properties')

        props.load(propsFile.newDataInputStream())

        int appCodeNumber = Integer.parseInt(props.getProperty('appCodeNumber'))
        appCodeNumber += 4

        int appVersionNumberIndex = Integer.parseInt(props.getProperty('appVersionNumberIndex'))
        appVersionNumberIndex += 1

        props.setProperty('appCodeNumber', "" + appCodeNumber)
        props.setProperty('appVersionNumberIndex', "" + appVersionNumberIndex)

        props.store(propsFile.newWriter(), null)

        println "My Task: [incVersion]"
    }
}

if (!taskName.contains("Fdroid")) {
    dependencies {
        implementation("com.github.junrar:junrar:4.0.0")
        implementation("com.google.android.gms:play-services-auth:21.4.0")
        implementation("com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0")
        implementation("com.google.api-client:google-api-client-android:2.8.0")
        implementation("com.google.oauth-client:google-oauth-client-jetty:1.39.0")
        implementation("com.google.http-client:google-http-client-gson:1.47.1")
    }
}

