import java.util.stream.Collectors

plugins {
    id 'com.android.library'
    id 'org.jetbrains.kotlin.android'
    id "de.undercouch.download"
}

Properties properties = new Properties()
if (rootProject.file("local.properties").exists()) {
    properties.load(rootProject.file("local.properties").newDataInputStream())
}

ext["keyId"] = properties.getProperty("signing.keyId", System.getenv('SIGNING_KEY_ID'))
ext["password"] = properties.getProperty("signing.password", System.getenv('SIGNING_PASSWORD'))
ext["key"] = properties.getProperty("signing.key", System.getenv('SIGNING_KEY'))
ext["ossrhUsername"] = properties.getProperty("ossrhUsername", System.getenv('OSSRH_USERNAME'))
ext["ossrhPassword"] = properties.getProperty("ossrhPassword", System.getenv('OSSRH_PASSWORD'))
ext["sonatypeStagingProfileId"] = properties.getProperty("sonatypeStagingProfileId", System.getenv('SONATYPE_STAGING_PROFILE_ID'))

ext {
    set("GROUP_ID", "org.kiwix.kiwixlib")
    set("ARTIFACT_ID", "kiwixlib")
    set("VERSION", "11.0.0")
}

apply from: 'publish.gradle'
android {
    compileSdk 32

    defaultConfig {

        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ''
                arguments "-DANDROID_STL=c++_shared", "-DBUILD_DIR=${buildDir}"
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    externalNativeBuild {
        cmake {
            path file('src/main/cpp/CMakeLists.txt')
            version '3.18.1'
        }
    }
    buildFeatures {
        viewBinding true
    }
    ndkVersion '21.4.7075529'

}

dependencies {
    implementation 'com.getkeepsafe.relinker:relinker:1.4.5'
    implementation 'androidx.core:core-ktx:1.7.0'
}

ext.libkiwix_base_url = 'https://download.kiwix.org/nightly'
ext.libzim_base_url = 'https://download.openzim.org/nightly'
// change this date to get latest libzim .so and header files
ext.nightly_date_for_libkiwix = project.properties["nightly_date_for_libkiwix"] ?: ""
ext.nightly_date_for_libkiwix_linux = project.properties["nightly_date_for_libkiwix_linux"] ?: ""
ext.nightly_date_for_libzim = project.properties["nightly_date_for_libzim"] ?: ""
ext.nightly_date_for_libzim_linux = project.properties["nightly_date_for_libzim_linux"] ?: ""

ext.libkiwix_version = project.properties["libkiwix_version"] ?: ""
ext.libzim_version = project.properties["libzim_version"] ?: ""

task downloadLibzimSoAndHeaderFiles(type: Download) {
    src([
            libzim_base_url + '/libzim_android-arm.tar.gz',
            libzim_base_url + '/libzim_android-arm64.tar.gz',
            libzim_base_url + '/libzim_android-x86.tar.gz',
            libzim_base_url + '/libzim_android-x86_64.tar.gz',
            libzim_base_url + '/libzim_linux-x86_64.tar.gz'
    ])
    dest buildDir
    overwrite true
}

task checkCurrentLibzimDate() {
    project.ext.set("nightly_date_for_libzim", getDateFromPath(buildDir.path, "libzim_android-arm64-"))
}

task checkCurrentLinuxLibzimDate() {
    project.ext.set("nightly_date_for_libzim_linux", getDateFromPath(buildDir.path, "libzim_linux-x86_64-"))
}

task unzipLibzim(type: Copy) {
    // unzip android arm
    from tarTree(buildDir.path + "/libzim_android-arm.tar.gz")
    into buildDir
    // unzip android arm64
    from tarTree(buildDir.path + "/libzim_android-arm64.tar.gz")
    into buildDir
    // unzip android x86
    from tarTree(buildDir.path + "/libzim_android-x86.tar.gz")
    into buildDir
    // unzip android x86_64
    from tarTree(buildDir.path + "/libzim_android-x86_64.tar.gz")
    into buildDir
    // unzip linux x86_64
    from tarTree(buildDir.path + "/libzim_linux-x86_64.tar.gz")
    into buildDir
}

task copyLibzimHeaderFiles(type: Copy) {
    // copying header file
    from buildDir.path + "/libzim_android-arm-" + nightly_date_for_libzim + '/include/'
    into buildDir.path + "/include/libzim/"
}

task copyLibzimAndroidArm(type: Copy) {
    // copying android_arm so file
    from buildDir.path + "/libzim_android-arm-" + nightly_date_for_libzim + '/lib/arm-linux-androideabi/'
    into buildDir.path + "/jniLibs/armeabi-v7a/libzim/"
}

task copyLibzimAndroidArm64(type: Copy) {
    // copying android_arm64 so file
    from buildDir.path + "/libzim_android-arm64-" + nightly_date_for_libzim + '/lib/aarch64-linux-android/'
    into buildDir.path + "/jniLibs/arm64-v8a/libzim/"
}

task copyLibzimAndroidx86(type: Copy) {
    // copying android_x86 so file
    from buildDir.path + "/libzim_android-x86-" + nightly_date_for_libzim + '/lib/i686-linux-android/'
    into buildDir.path + "/jniLibs/x86/libzim/"
}

task copyLibzimAndroidx86_64(type: Copy) {
    // copying android_x86_64 so file
    from buildDir.path + "/libzim_android-x86_64-" + nightly_date_for_libzim + '/lib/x86_64-linux-android/'
    into buildDir.path + "/jniLibs/x86_64/libzim/"
}

task copyLibzimLinux_x86_64(type: Copy) {
    // copying linux_x86_64 so file
    project.ext.set("libzim_version", getFileFromFolder(buildDir.path + "/libzim_linux-x86_64-" + nightly_date_for_libzim_linux + "/lib/x86_64-linux-gnu/"))
    from buildDir.path + "/libzim_linux-x86_64-" + nightly_date_for_libzim_linux + "/lib/x86_64-linux-gnu/" + libzim_version
    into buildDir.path
}

task renameLibzimSoFile(type: Copy) {
    if (libzim_version != null) {
        from(buildDir.path)
        include libzim_version
        destinationDir file(buildDir.path)
        rename libzim_version, "libzim.so"
    }
}

task downloadLibkiwixSoAndHeaderFiles(type: Download) {
    src([
            libkiwix_base_url + '/libkiwix_android-arm.tar.gz',
            libkiwix_base_url + '/libkiwix_android-arm64.tar.gz',
            libkiwix_base_url + '/libkiwix_android-x86.tar.gz',
            libkiwix_base_url + '/libkiwix_android-x86_64.tar.gz',
            libkiwix_base_url + '/libkiwix_linux-x86_64.tar.gz'
    ])
    dest buildDir
    overwrite true
}

task checkCurrentLibkiwixDate() {
    project.ext.set("nightly_date_for_libkiwix", getDateFromPath(buildDir.path, "libkiwix_android-arm64-"))
}

task checkCurrentLinuxLibkiwixDate() {
    project.ext.set("nightly_date_for_libkiwix_linux", getDateFromPath(buildDir.path, "libkiwix_linux-x86_64-"))
}

static String getDateFromPath(String path, String matchesString) {
    File folder = new File(path)
    if (folder.exists()) {
        return folder.listFiles()
                .stream()
                .filter(f -> f.name.startsWith(matchesString))
                .map(s -> s.name.replace(matchesString, ""))
                .collect(Collectors.toList())[0]
    }
}

task unzipLibkiwix(type: Copy) {
    // unzip android arm
    from tarTree(buildDir.path + "/libkiwix_android-arm.tar.gz")
    into buildDir
    // unzip android arm64
    from tarTree(buildDir.path + "/libkiwix_android-arm64.tar.gz")
    into buildDir
    // unzip android x86
    from tarTree(buildDir.path + "/libkiwix_android-x86.tar.gz")
    into buildDir
    // unzip android x86_64
    from tarTree(buildDir.path + "/libkiwix_android-x86_64.tar.gz")
    into buildDir
    // unzip linux x86_64
    from tarTree(buildDir.path + "/libkiwix_linux-x86_64.tar.gz")
    into buildDir
}

task copyLibkiwixHeaderFiles(type: Copy) {
    // copying header file
    from buildDir.path + "/libkiwix_android-arm-" + nightly_date_for_libkiwix + '/include/kiwix/'
    into buildDir.path + "/include/libkiwix/"
}

task copyLibkiwixAndroidArm(type: Copy) {
    // copying android_arm so file
    from buildDir.path + "/libkiwix_android-arm-" + nightly_date_for_libkiwix + '/lib/arm-linux-androideabi/'
    into buildDir.path + "/jniLibs/armeabi-v7a/libkiwix/"
}

task copyLibkiwixAndroidArm64(type: Copy) {
    // copying android_arm64 so file
    from buildDir.path + "/libkiwix_android-arm64-" + nightly_date_for_libkiwix + '/lib/aarch64-linux-android/'
    into buildDir.path + "/jniLibs/arm64-v8a/libkiwix/"
}

task copyLibkiwixAndroidx86(type: Copy) {
    // copying android_x86 so file
    from buildDir.path + "/libkiwix_android-x86-" + nightly_date_for_libkiwix + '/lib/i686-linux-android/'
    into buildDir.path + "/jniLibs/x86/libkiwix/"
}

task copyLibkiwixAndroidx86_64(type: Copy) {
    // copying android_x86_64 so file
    from buildDir.path + "/libkiwix_android-x86_64-" + nightly_date_for_libkiwix + '/lib/x86_64-linux-android/'
    into buildDir.path + "/jniLibs/x86_64/libkiwix/"
}

task copyLibkiwixLinux_x86_64(type: Copy) {
    // copying linux_x86_64 so file
    project.ext.set("libkiwix_version", getFileFromFolder(buildDir.path + "/libkiwix_linux-x86_64-" + nightly_date_for_libkiwix_linux + "/lib/x86_64-linux-gnu/"))
    from buildDir.path + "/libkiwix_linux-x86_64-" + nightly_date_for_libkiwix_linux + "/lib/x86_64-linux-gnu/" + libkiwix_version
    into buildDir.path
}

static String getFileFromFolder(String path) {
    File folderFile = new File(path)
    if (folderFile.exists()) {
        return folderFile.listFiles()
                .stream()
                .filter(f -> f.length() > 0)
                .collect(Collectors.toList())[0].name
    }
}

task renameLibkiwixSoFile(type: Copy) {
    if (libkiwix_version != null) {
        from(buildDir.path)
        include libkiwix_version
        destinationDir file(buildDir.path)
        rename libkiwix_version, "libkiwix.so"
    }
}

task copyBuildKiwixSoFile(type: Copy) {
    // copying linux_x86_64 so file
    from projectDir.path + "/src/test/libbuildkiwix.so"
    into buildDir.path
}

task createCodeCoverageReport(type: Exec) {
    workingDir "${projectDir}/src/test/"
    commandLine 'sh', '-c', "bash 'compile_and_run_test.sh' ${buildDir}/libs/*lib*.jar $buildDir"
}

task checkCurrentJavaVersion() {
    if (JavaVersion.current() != JavaVersion.VERSION_11) {
        throw new RuntimeException("This build must be run with java 11. your current java version is ${JavaVersion.current()}")
    }
}


task generateHeaderFilesFromJavaWrapper(type: Exec) {
    workingDir "${projectDir}/src/main/java/org/kiwix/"
    commandLine 'bash', '-c', "javac -h ${buildDir}/include/javah_generated/ -d ${projectDir}/src/test/ ${getLibzimFiles()} ${getLibkiwixFiles()}"
}

String getLibkiwixFiles() {
    return "${projectDir}/src/main/java/org/kiwix/libkiwix/Book.java " +
        "${projectDir}/src/main/java/org/kiwix/libkiwix/Bookmark.java " +
        "${projectDir}/src/main/java/org/kiwix/libkiwix/Filter.java " +
        "${projectDir}/src/main/java/org/kiwix/libkiwix/JNIICU.java " +
        "${projectDir}/src/main/java/org/kiwix/libkiwix/Illustration.java " +
        "${projectDir}/src/main/java/org/kiwix/libkiwix/JNIKiwixException.java " +
        "${projectDir}/src/main/java/org/kiwix/libkiwix/Library.java " +
        "${projectDir}/src/main/java/org/kiwix/libkiwix/Manager.java " +
        "${projectDir}/src/main/java/org/kiwix/libkiwix/Server.java"
}

String getLibzimFiles() {
    return "${projectDir}/src/main/java/org/kiwix/libzim/Archive.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/Blob.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/DirectAccessInfo.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/EntryIterator.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/Entry.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/Item.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/Query.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/Searcher.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/SearchIterator.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/Search.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/SuggestionItem.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/SuggestionIterator.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/SuggestionSearcher.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/SuggestionSearch.java " +
        "${projectDir}/src/main/java/org/kiwix/libzim/ZimFileFormatException.java"
}
