package de.datait.videokonverter

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.webkit.CookieManager
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.media3.ui.PlayerView
import androidx.preference.PreferenceManager

/**
 * Haupt-Activity: WebView laedt die TV-App vom Server.
 * ExoPlayer-Overlay fuer Direct-Play Video.
 */
class MainActivity : AppCompatActivity() {

    private lateinit var webView: WebView
    private lateinit var playerView: PlayerView
    private lateinit var bridge: NativePlayerBridge
    private var serverUrl: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Immersive Fullscreen: Status- und Navigationsleiste verstecken
        WindowCompat.setDecorFitsSystemWindows(window, false)
        val insetsController = WindowInsetsControllerCompat(window, window.decorView)
        insetsController.hide(WindowInsetsCompat.Type.systemBars())
        insetsController.systemBarsBehavior =
            WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE

        setContentView(R.layout.activity_main)

        // Server-URL aus Intent oder Preferences
        serverUrl = intent.getStringExtra("server_url")
            ?: PreferenceManager.getDefaultSharedPreferences(this)
                .getString("server_url", null)
            ?: run {
                // Keine URL -> zurueck zum Setup
                startActivity(Intent(this, SetupActivity::class.java))
                finish()
                return
            }

        webView = findViewById(R.id.webview)
        playerView = findViewById(R.id.playerView)

        // Cookies aktivieren (fuer Auth-Session)
        CookieManager.getInstance().apply {
            setAcceptCookie(true)
            setAcceptThirdPartyCookies(webView, true)
        }

        // WebView konfigurieren
        webView.settings.apply {
            javaScriptEnabled = true
            domStorageEnabled = true
            mediaPlaybackRequiresUserGesture = false
            mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            // Cache-Einstellungen
            cacheMode = WebSettings.LOAD_DEFAULT
            databaseEnabled = true
        }

        // NativePlayerBridge registrieren
        bridge = NativePlayerBridge(this, webView, playerView, serverUrl)
        webView.addJavascriptInterface(bridge, "VKNativeAndroid")

        // Custom WebViewClient: VKNative nach jedem Page-Load injizieren
        webView.webViewClient = VKWebViewClient(serverUrl)

        // Custom WebChromeClient: Fullscreen + Console-Logs
        webView.webChromeClient = VKWebChromeClient()

        // TV-App laden
        webView.loadUrl("$serverUrl/tv/")
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // ExoPlayer aktiv? Zuerst stoppen
            if (playerView.visibility == View.VISIBLE) {
                bridge.stop()
                return true
            }
            // WebView zurueck-navigieren
            if (webView.canGoBack()) {
                webView.goBack()
                return true
            }
            // Kein Zurueck moeglich -> zurueck zum Setup (Server aendern)
            val intent = Intent(this, SetupActivity::class.java)
            intent.putExtra("force_setup", true)
            startActivity(intent)
            finish()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        // Immersive Mode nach Focus-Wechsel neu setzen (Android setzt es zurueck)
        if (hasFocus) {
            val insetsController = WindowInsetsControllerCompat(window, window.decorView)
            insetsController.hide(WindowInsetsCompat.Type.systemBars())
            insetsController.systemBarsBehavior =
                WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }
    }

    override fun onPause() {
        super.onPause()
        // ExoPlayer pausieren wenn App in den Hintergrund geht
        bridge.pauseIfPlaying()
    }

    override fun onDestroy() {
        bridge.release()
        webView.destroy()
        super.onDestroy()
    }
}
