package com.ponzischeme89.memby.ui.screensaver

import android.os.Bundle
import android.os.Build
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.ponzischeme89.memby.ui.player.PlayerActivity
import com.ponzischeme89.memby.ui.theme.MembyTheme

/** In-app preview of the screensaver, launched from the home screen. */
class ScreensaverActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        // A package replacement can leave Android TV in the Dream's ambient/sleeping
        // state. The restart destination is an interactive slide, so wake the display
        // as this activity becomes visible instead of rendering it behind black.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setTurnScreenOn(true)
        } else {
            @Suppress("DEPRECATION")
            window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON)
        }
        setContent {
            MembyTheme {
                ScreensaverContent(
                    onPlay = { url, title ->
                        startActivity(PlayerActivity.intent(this, url, title))
                    },
                    onExit = { finish() },
                    startupMessage = intent.getStringExtra(EXTRA_STARTUP_MESSAGE),
                )
            }
        }
    }

    companion object {
        const val EXTRA_STARTUP_MESSAGE = "com.ponzischeme89.memby.extra.STARTUP_MESSAGE"

        fun restartAfterUpdateIntent(context: android.content.Context): android.content.Intent =
            android.content.Intent(context, ScreensaverActivity::class.java)
                .putExtra(EXTRA_STARTUP_MESSAGE, "Restarting Memby after update…")
    }
}
