package com.ponzischeme89.memby.ui.screensaver

import android.content.Context
import android.content.Intent
import androidx.core.net.toUri

/** Opens an item in Emby's installed Android or Android TV client. */
internal object EmbyAppLauncher {
    private val packageCandidates = listOf("com.mb.android", "tv.emby.embyatv")

    fun play(context: Context, serverId: String?, itemId: String): Boolean {
        if (serverId.isNullOrBlank() || itemId.isBlank()) return false

        // `play` is supported by recent Emby Android builds. `items` keeps navigation
        // useful for older installed clients that only support opening an item page.
        val links = listOf(
            "emby://play/$serverId/$itemId",
            "emby://items/$serverId/$itemId",
        )
        for (packageName in packageCandidates) {
            for (link in links) {
                val intent = Intent(Intent.ACTION_VIEW, link.toUri())
                    .setPackage(packageName)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                if (intent.resolveActivity(context.packageManager) != null) {
                    context.startActivity(intent)
                    return true
                }
            }
        }
        return false
    }
}
