Pith - spline
package com.vgmlr.spline

import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import android.os.Environment
import android.provider.Settings
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

internal object SplineInstall {
    private const val APK = "application/vnd.android.package-archive"
    private const val POLL_MS = 500L
    private const val TIMEOUT = 15_000
    private val DIRECT = setOf(APK, "application/octet-stream")

    fun canInstall(ctx: Context): Boolean = ctx.packageManager.canRequestPackageInstalls()

    fun sources(ctx: Context): Intent =
        Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, "package:${ctx.packageName}".toUri())

    private fun dm(ctx: Context): DownloadManager =
        ctx.getSystemService(DownloadManager::class.java)

    // apk check
    fun direct(url: String): Boolean =
        probe(url, "HEAD") ?: probe(url, "GET") ?: false

    // null = inconclusive
    private fun probe(url: String, method: String): Boolean? =
        try {
            val c = URL(url).openConnection() as? HttpURLConnection ?: return null
            try {
                c.requestMethod = method
                c.instanceFollowRedirects = true
                c.connectTimeout = TIMEOUT
                c.readTimeout = TIMEOUT
                if (c.responseCode !in 200..299) null
                else {
                    val type = c.contentType.orEmpty()
                        .substringBefore(';').trim().lowercase()
                    val disp = c.getHeaderField("Content-Disposition").orEmpty().lowercase()
                    type in DIRECT || ".apk" in disp
                }
            } finally {
                c.disconnect()
            }
        } catch (e: IOException) {
            null
        }

    fun browse(ctx: Context, url: String): Boolean =
        runCatching {
            ctx.startActivity(
                Intent(Intent.ACTION_VIEW, url.toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            )
        }.isSuccess
    
    fun enqueue(ctx: Context, app: SplineApp): Long {
        val req = DownloadManager.Request(app.apk.toUri())
            .setTitle(app.name)
            .setDescription(app.version)
            .setMimeType(APK)
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
            .setDestinationInExternalPublicDir(
                Environment.DIRECTORY_DOWNLOADS,
                "${app.id}_${app.version}.apk"
            )
        val dl = dm(ctx).enqueue(req)
        SplinePrefs.addPending(ctx, SplinePending(dl, app.id, app.version))
        return dl
    }

    suspend fun await(ctx: Context, dl: Long, onProgress: (Float) -> Unit = {}): Boolean {
        val dm = dm(ctx)
        while (true) {
            val s = withContext(Dispatchers.IO) { snap(dm, dl) } ?: return false
            if (s.total > 0) onProgress((s.done.toFloat() / s.total).coerceIn(0f, 1f))
            when (s.status) {
                DownloadManager.STATUS_SUCCESSFUL -> {
                    onProgress(1f)
                    return true
                }
                DownloadManager.STATUS_FAILED -> return false
            }
            delay(POLL_MS)
        }
    }

    @Suppress("DEPRECATION")
    fun intent(ctx: Context, dl: Long): Intent? {
        val uri = dm(ctx).getUriForDownloadedFile(dl) ?: return null
        return Intent(Intent.ACTION_INSTALL_PACKAGE)
            .setDataAndType(uri, APK)
            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            .putExtra(Intent.EXTRA_RETURN_RESULT, true)
    }

    fun discard(ctx: Context, dl: Long) {
        dm(ctx).remove(dl)
        SplinePrefs.removePending(ctx, dl)
    }

    fun discardFor(ctx: Context, id: String) {
        SplinePrefs.pending(ctx).filter { it.id == id }.forEach { discard(ctx, it.dl) }
    }

    fun sweep(ctx: Context) {
        val dm = dm(ctx)
        val pm = ctx.packageManager
        SplinePrefs.pending(ctx).forEach { p ->
            val local = SplineRepo.local(pm, p.id)
            val st = status(dm, p.dl)
            when {
                local != null && SplineRepo.cmp(local, p.version) >= 0 -> discard(ctx, p.dl)
                st == null -> SplinePrefs.removePending(ctx, p.dl)
                st == DownloadManager.STATUS_FAILED -> discard(ctx, p.dl)
            }
        }
    }

    private class Snap(val status: Int, val done: Long, val total: Long)

    private fun status(dm: DownloadManager, dl: Long): Int? = snap(dm, dl)?.status

    private fun snap(dm: DownloadManager, dl: Long): Snap? =
        dm.query(DownloadManager.Query().setFilterById(dl))?.use { c ->
            if (c.moveToFirst()) Snap(
                c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)),
                c.getLong(c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)),
                c.getLong(c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
            ) else null
        }
}