Pith - spline
package com.vgmlr.spline

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import kotlin.math.max

internal data class SplineApp(
    val name: String,
    val desc: String,
    val id: String,
    val version: String,
    val apk: String,
    val icon: String,
    val url: String
)

internal data class SplineEntry(val app: SplineApp, val local: String?) {
    val newer: Boolean get() = local != null && SplineRepo.cmp(app.version, local) > 0
}

internal object SplineRepo {
    private const val SRC = "https://vgmlr.com/mlwrk/spline.txt"
    private const val CACHE = "spline.txt"
    private const val TIMEOUT = 15_000
    private const val FIELDS = 7

    fun parse(text: String): List<SplineApp> =
        text.removePrefix("\uFEFF").lineSequence()
            .map { it.trim() }
            .filter { it.isNotEmpty() }
            .mapNotNull { line ->
                val f = line.split('|').map { it.trim() }
                if (f.size < FIELDS || f[2].isEmpty()) null
                else SplineApp(f[0], f[1], f[2], f[3], f[4], f[5], f[6])
            }
            .distinctBy { it.id }
            .toList()

    fun cached(ctx: Context): List<SplineApp> =
        try {
            File(ctx.filesDir, CACHE).takeIf { it.isFile }?.readText()?.let(::parse).orEmpty()
        } catch (e: IOException) {
            emptyList()
        }

    suspend fun scan(ctx: Context): Boolean = withContext(Dispatchers.IO) {
        val text = fetch() ?: return@withContext false
        if (parse(text).isEmpty()) return@withContext false
        try {
            val tmp = File.createTempFile("spline", ".tmp", ctx.filesDir)
            tmp.writeText(text)
            if (!tmp.renameTo(File(ctx.filesDir, CACHE))) {
                tmp.delete()
                return@withContext false
            }
        } catch (e: IOException) {
            return@withContext false
        }
        SplinePrefs.setLastScan(ctx, System.currentTimeMillis())
        true
    }

    fun entries(ctx: Context, apps: List<SplineApp>): List<SplineEntry> {
        val pm = ctx.packageManager
        return apps.map { SplineEntry(it, local(pm, it.id)) }
            .sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.app.name })
    }

    fun updates(entries: List<SplineEntry>): Int = entries.count { it.newer }

    fun local(pm: PackageManager, id: String): String? =
        try {
            info(pm, id).versionName ?: "0"
        } catch (e: PackageManager.NameNotFoundException) {
            null
        }

    fun cmp(a: String, b: String): Int {
        val x = a.split('.').map { it.trim().toIntOrNull() ?: 0 }
        val y = b.split('.').map { it.trim().toIntOrNull() ?: 0 }
        for (i in 0 until max(x.size, y.size)) {
            val d = x.getOrElse(i) { 0 }.compareTo(y.getOrElse(i) { 0 })
            if (d != 0) return d
        }
        return 0
    }

    private fun info(pm: PackageManager, id: String): PackageInfo =
        if (Build.VERSION.SDK_INT >= 33) {
            pm.getPackageInfo(id, PackageManager.PackageInfoFlags.of(0))
        } else {
            @Suppress("DEPRECATION")
            pm.getPackageInfo(id, 0)
        }

    private fun fetch(): String? =
        try {
            val c = URL(SRC).openConnection() as HttpURLConnection
            try {
                c.connectTimeout = TIMEOUT
                c.readTimeout = TIMEOUT
                c.useCaches = false
                c.setRequestProperty("Cache-Control", "no-cache")
                if (c.responseCode == HttpURLConnection.HTTP_OK) {
                    c.inputStream.bufferedReader().use { it.readText() }
                } else null
            } finally {
                c.disconnect()
            }
        } catch (e: IOException) {
            null
        }
}