package de.datait.videokonverter

import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient

/**
 * Custom WebViewClient: Injiziert VKNative Bridge nach jedem Page-Load.
 * Haelt Navigation innerhalb der App (kein externer Browser).
 */
class VKWebViewClient(private val serverUrl: String) : WebViewClient() {

    override fun onPageFinished(view: WebView, url: String) {
        super.onPageFinished(view, url)

        // VKNative Bridge in JavaScript injizieren
        // VKNativeAndroid ist per @JavascriptInterface registriert,
        // muss aber zu window.VKNative gewrapped werden (korrekte API)
        val js = """
            (function() {
                if (window.VKNative) return;
                if (!window.VKNativeAndroid) return;

                window.VKNative = {
                    platform: 'android',
                    version: '1.0.0',

                    getSupportedVideoCodecs: function() {
                        try { return JSON.parse(VKNativeAndroid.getSupportedVideoCodecs()); }
                        catch(e) { return ['h264']; }
                    },
                    getSupportedAudioCodecs: function() {
                        try { return JSON.parse(VKNativeAndroid.getSupportedAudioCodecs()); }
                        catch(e) { return ['aac']; }
                    },
                    canDirectPlay: function(videoInfo) {
                        try { return VKNativeAndroid.canDirectPlay(JSON.stringify(videoInfo)); }
                        catch(e) { return false; }
                    },
                    play: function(url, videoInfo, opts) {
                        try {
                            return VKNativeAndroid.play(url,
                                JSON.stringify(videoInfo || {}),
                                JSON.stringify(opts || {}));
                        } catch(e) { return false; }
                    },
                    togglePlay: function() { VKNativeAndroid.togglePlay(); },
                    pause: function() { VKNativeAndroid.pause(); },
                    resume: function() { VKNativeAndroid.resume(); },
                    seek: function(ms) { VKNativeAndroid.seek(ms); },
                    getCurrentTime: function() { return VKNativeAndroid.getCurrentTime(); },
                    getDuration: function() { return VKNativeAndroid.getDuration(); },
                    isPlaying: function() { return VKNativeAndroid.isPlaying(); },
                    stop: function() { VKNativeAndroid.stop(); },
                    playHLS: function(url, opts) {
                        try { return VKNativeAndroid.playHLS(url, JSON.stringify(opts || {})); }
                        catch(e) { return false; }
                    },
                    setAudioTrack: function(i) { return VKNativeAndroid.setAudioTrack(i); },
                    setSubtitleTrack: function(i) { return VKNativeAndroid.setSubtitleTrack(i); },
                    setPlaybackSpeed: function(s) { return VKNativeAndroid.setPlaybackSpeed(s); },
                };

                console.info('[VKNative] Android Bridge initialisiert');
            })();
        """.trimIndent()

        view.evaluateJavascript(js, null)
    }

    override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
        val url = request.url.toString()
        // Nur Server-URLs in der WebView oeffnen
        if (url.startsWith(serverUrl) || url.startsWith("http://") || url.startsWith("https://")) {
            return false // WebView handelt die URL
        }
        return true // Andere URLs blockieren
    }
}
