package com.ponzischeme89.memby.update

import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import androidx.core.net.toUri

/**
 * The per-app "install unknown apps" permission, which is what actually decides whether
 * Memby can ever update itself.
 *
 * Every television here is sideloaded, in practice through Downloader — which means
 * *Downloader* holds this permission and Memby does not. Nothing in a fresh install asks for
 * it, so the first time anyone finds out is halfway through an update that then refuses to
 * proceed. Asking during setup, while somebody is sitting in front of the TV expecting to be
 * asked things, is the whole point of [com.ponzischeme89.memby.ui.InstallPermissionScreen].
 */
object InstallPermission {

    /** Where the setting lives on a television, for when there is no screen to open. */
    const val MANUAL_PATH =
        "Settings → Device Preferences → Security & restrictions → Unknown sources"

    fun granted(context: Context): Boolean =
        Build.VERSION.SDK_INT < Build.VERSION_CODES.O ||
            context.packageManager.canRequestPackageInstalls()

    /**
     * Opens Android's per-app permission screen.
     *
     * Returns false when this TV has no such screen — several do not, and the difference
     * between "not granted yet" and "nowhere to grant it" is the difference between a
     * prompt that works and one that silently does nothing.
     */
    fun requestScreen(context: Context): Boolean {
        val intent = Intent(
            Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
            "package:${context.packageName}".toUri(),
        ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        return runCatching { context.startActivity(intent) }.isSuccess
    }
}
