package com.ponzischeme89.memby.update

/**
 * Whether a remembered refusal has been answered by the build now running.
 *
 * The refusal is stored as the version the gateway demanded, and the only thing that can
 * genuinely satisfy it without asking the server is this television having reached that
 * version — which is exactly what happens after the update installs and the app restarts
 * before its first check comes back. Without this the freshly updated build would open on
 * the retired-build screen it had just escaped.
 *
 * A version this build cannot parse is treated as *not* satisfied: the refusal stands
 * until the gateway itself withdraws it, because guessing the other way would let a
 * malformed policy value put a retired television back on the launcher.
 */
fun requiredUpdateSatisfied(installedVersion: String, requiredVersion: String): Boolean {
    val required = parseAppVersion(requiredVersion)
    val installed = parseAppVersion(installedVersion)
    if (required.isEmpty() || installed.isEmpty()) return false
    for (index in 0 until maxOf(required.size, installed.size)) {
        val demanded = required.getOrElse(index) { 0 }
        val running = installed.getOrElse(index) { 0 }
        if (demanded != running) return running > demanded
    }
    return true
}

/** Stops at the first non-numeric component, so `0.2.46-beta` reads as 0.2.46. */
private fun parseAppVersion(version: String): List<Int> {
    val parts = version.trim().trimStart('v', 'V').split('.', '-', '+', ' ')
    val out = mutableListOf<Int>()
    for (part in parts) {
        val value = part.toIntOrNull() ?: break
        out += value
    }
    return out
}
