package com.demoscene.tv

import android.os.Bundle
import android.view.KeyEvent
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.FragmentActivity

/**
 * Activity for playing YouTube videos in fullscreen
 */
class PlayerActivity : FragmentActivity() {

    private lateinit var webView: WebView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_player)

        val demoTitle = intent.getStringExtra("DEMO_TITLE") ?: "Demo"
        val youtubeUrl = intent.getStringExtra("DEMO_YOUTUBE_URL") ?: ""
        val group = intent.getStringExtra("DEMO_GROUP") ?: ""
        val year = intent.getIntExtra("DEMO_YEAR", 0)
        val platform = intent.getStringExtra("DEMO_PLATFORM") ?: ""

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

        if (youtubeUrl.isNotEmpty()) {
            loadYouTubeVideo(youtubeUrl)
        }
    }

    private fun setupWebView() {
        webView.settings.apply {
            javaScriptEnabled = true
            domStorageEnabled = true
            mediaPlaybackRequiresUserGesture = false
        }

        webView.webChromeClient = WebChromeClient()
        webView.webViewClient = WebViewClient()
    }

    private fun loadYouTubeVideo(youtubeUrl: String) {
        // Extract video ID from YouTube URL
        val videoId = extractYouTubeVideoId(youtubeUrl)
        
        // Create embedded player HTML
        val html = """
            <!DOCTYPE html>
            <html>
            <head>
                <style>
                    body { margin: 0; padding: 0; background: #000; }
                    #player { 
                        position: absolute; 
                        top: 0; 
                        left: 0; 
                        width: 100%; 
                        height: 100%; 
                    }
                </style>
            </head>
            <body>
                <div id="player"></div>
                <script>
                    var tag = document.createElement('script');
                    tag.src = "https://www.youtube.com/iframe_api";
                    var firstScriptTag = document.getElementsByTagName('script')[0];
                    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
                    
                    var player;
                    function onYouTubeIframeAPIReady() {
                        player = new YT.Player('player', {
                            videoId: '$videoId',
                            playerVars: {
                                'autoplay': 1,
                                'controls': 1,
                                'showinfo': 0,
                                'modestbranding': 1,
                                'fs': 1
                            },
                            events: {
                                'onReady': onPlayerReady
                            }
                        });
                    }
                    
                    function onPlayerReady(event) {
                        event.target.playVideo();
                    }
                </script>
            </body>
            </html>
        """.trimIndent()

        webView.loadDataWithBaseURL("https://www.youtube.com", html, "text/html", "UTF-8", null)
    }

    private fun extractYouTubeVideoId(url: String): String {
        // Handle various YouTube URL formats
        val patterns = listOf(
            "(?<=watch\\?v=)[^&]+",
            "(?<=youtu.be/)[^?]+",
            "(?<=embed/)[^?]+"
        )

        for (pattern in patterns) {
            val regex = Regex(pattern)
            val match = regex.find(url)
            if (match != null) {
                return match.value
            }
        }

        return ""
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // Back button exits player
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

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