apply plugin: 'com.android.application'
apply plugin: 'com.google.devtools.ksp'

import com.android.build.api.variant.FilterConfiguration
import groovy.xml.XmlParser
import groovy.xml.XmlUtil

android {
    buildFeatures {
        viewBinding = true
    }
    compileSdk = 37
    namespace = "net.mediaarea.mediainfo"
    defaultConfig {
        applicationId "net.mediaarea.mediainfo"
        multiDexEnabled = true
        minSdkVersion 21
        versionCode 17
        versionName "26.05.20260606"
        targetSdkVersion 37
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary = true
        }
        externalNativeBuild {
            cmake {
                arguments "-DENABLE_UNICODE=ON",
                        "-DMEDIAINFO_ADVANCED=OFF",
                        "-DMEDIAINFO_AES=OFF",
                        "-DMEDIAINFO_DEMUX=OFF",
                        "-DMEDIAINFO_DIRECTORY=OFF",
                        "-DMEDIAINFO_DUPLICATE=OFF",
                        "-DMEDIAINFO_DVDIF_ANALYZE=OFF",
                        "-DMEDIAINFO_EVENTS=OFF",
                        "-DMEDIAINFO_FILTER=OFF",
                        "-DMEDIAINFO_FIXITY=OFF",
                        "-DMEDIAINFO_GRAPH=OFF",
                        "-DMEDIAINFO_IBI=OFF",
                        "-DMEDIAINFO_LIBCURL=OFF",
                        "-DMEDIAINFO_LIBMMS=OFF",
                        "-DMEDIAINFO_MACROBLOCKS=OFF",
                        "-DMEDIAINFO_MD5=OFF",
                        "-DMEDIAINFO_NEXTPACKET=OFF",
                        "-DMEDIAINFO_READER=OFF",
                        "-DMEDIAINFO_READTHREAD=OFF",
                        "-DMEDIAINFO_REFERENCES=OFF",
                        "-DMEDIAINFO_SHA1=OFF",
                        "-DMEDIAINFO_SHA2=OFF",
                        "-DMEDIAINFO_TRACE=OFF",
                        "-DMEDIAINFO_TRACE_FFV1CONTENT=OFF"
            }
        }
        splits {
            abi {
                reset()
                include 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
            }
        }
        if(project.hasProperty("RELEASE_STORE_FILE")) {
            signingConfigs {
                release {
                    storeFile file(RELEASE_STORE_FILE)
                    storePassword RELEASE_STORE_PASSWORD
                    keyAlias RELEASE_KEY_ALIAS
                    keyPassword RELEASE_KEY_PASSWORD
                }
            }
        }
    }
    buildTypes {
        release {
            if(project.hasProperty("RELEASE_STORE_FILE")) {
                signingConfig signingConfigs.release
            }
            minifyEnabled true
            shrinkResources = true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
    splits {
        abi {
            def isBuildingBundle = gradle.startParameter.taskNames.any { it.toLowerCase().contains('bundle') }
            enable = !isBuildingBundle

            universalApk = true
        }
    }
    bundle {
        language {
            enableSplit = false
        }
    }
    compileOptions {
        targetCompatibility JavaVersion.VERSION_21
        sourceCompatibility JavaVersion.VERSION_21
    }
}

androidComponents {
    def abiCodes = ['armeabi-v7a': 1, 'arm64-v8a': 2, 'x86': 3, 'x86_64': 4]
    onVariants(selector().all()) { variant ->
        // Assigns a different version code for each output APK.
        variant.outputs.forEach { output ->
            def abiFilter = output.filters.find { it.filterType == FilterConfiguration.FilterType.ABI }
            def abiName = abiFilter?.identifier
            def currentCode = output.versionCode.getOrElse(0)
            def offset = 0
            if (abiName != null)
                offset = abiCodes.get(abiName, 0)
            output.versionCode.set(currentCode * 10 + offset)
        }
    }
}

tasks.register('copyLocales', DefaultTask) {
    def locales = [:]

    fileTree("../../../../Source/Resource/Plugin/Language").visit { FileVisitDetails details ->
        def locale = details.file.name.replace(".csv", "").replace("-", "-r")
        if (locale == "gr") {
            locale = "el"
        }

        // copy localized csv into raw resources
        def raw = "src/main/res/raw-" + locale

        if (details.file.name == "en.csv") {
            raw = "src/main/res/raw"
        }

        mkdir raw
        copy {
            from details.file
            into raw
            rename { "lang.csv" }
        }

        //  update translations xml
        def csv = [:]
        file(details.file).splitEachLine(";") {
            if(it.size()==2 && it[0].size() && it[1].size()) {
                csv[it[0]] = it[1]
            }
        }
        def xml = new XmlParser().parse(file("src/main/res/values/strings.xml"))
        xml.string.each {
            if (it.@translatable == "false" || it.@csv == null || !csv.containsKey(it.@csv)) {
                xml.remove(it)
            }
            else {
                it.value = csv[it.@csv].replaceAll("\\\\r", "").replaceAll("'", "\\\\'").replaceAll("\"", "\\\\\"")
            }
        }

        if (xml.children().size()) {
            def values = "src/main/res/values-" + locale
            mkdir values

            def writer = file(values + "/strings.xml").newPrintWriter("UTF-8") // PrintWriter truncates file before write
            new XmlUtil().serialize(xml, writer)
            writer.close()
            //add locale to list
            locales[csv["  Language_Name"]] = locale
        }
    }

    // update translations list
    def xml = new XmlParser().parse(file("src/main/res/values/arrays.xml"))
    def locales_array = xml.find { it."@name" == "locales" }
    def locales_values_array = xml.find { it."@name" == "locales_values" }

    locales_array.item.each {
        if (locales_array.children().indexOf(it) > 0) {
            locales_array.remove(it)
        }
    }

    locales_values_array.item.each {
        if (locales_values_array.children().indexOf(it) > 0) {
            locales_values_array.remove(it)
        }
    }

    locales.sort().each { lang ->
        def name = new NodeBuilder().item(lang.key)
        locales_array.append(name)

        def value = new NodeBuilder().item(lang.value)
        locales_values_array.append(value)
    }

    def writer = file("src/main/res/values/arrays.xml").newPrintWriter("UTF-8") // PrintWriter truncates file before write
    new XmlUtil().serialize(xml, writer)
    writer.close()
}

preBuild.dependsOn copyLocales

dependencies {
    implementation 'com.google.android.material:material:1.13.0' // can only upgrade when minSdkVersion >= 23
    implementation 'androidx.appcompat:appcompat:1.7.1'
    implementation "androidx.core:core-ktx:1.17.0" // can only upgrade when minSdkVersion >= 23
    implementation 'androidx.documentfile:documentfile:1.1.0'
    implementation 'androidx.preference:preference-ktx:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.2.1'
    implementation 'androidx.recyclerview:recyclerview:1.4.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test:runner:1.7.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.7.0'
    // Android Room
    // can only upgrade when minSdkVersion >= 23
    implementation 'androidx.room:room-runtime:2.7.2'
    implementation 'androidx.room:room-ktx:2.7.2'
    ksp 'androidx.room:room-compiler:2.7.2'
    // Android Lifecycle
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    ksp "androidx.lifecycle:lifecycle-common-java8:2.10.0"
    // Google Billing
    // can only upgrade when minSdkVersion >= 23
    implementation "com.android.billingclient:billing:8.0.0"
    implementation "com.android.billingclient:billing-ktx:8.0.0"
    // KotlinX Coroutines
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0"
    // Locales manager
    implementation 'com.github.YarikSOffice:lingver:1.3.0'
}
