package com.example.daydreamclock

import android.service.dreams.DreamService
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import androidx.webkit.WebViewAssetLoader

class ClockDreamService : DreamService() {

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()

        // Setup interactive and fullscreen
        isInteractive = false
        isFullscreen = true

        setContentView(R.layout.layout_dream)

        val webView = findViewById<WebView>(R.id.dreamWebView)
        
        // AssetLoader setup to serve files from app assets via a virtual domain
        // This solves CORS issues with "file://" and ES Modules
        val assetLoader = WebViewAssetLoader.Builder()
            .addPathHandler("/assets/", WebViewAssetLoader.AssetsPathHandler(this))
            .build()

        webView.run {
            settings.javaScriptEnabled = true
            settings.domStorageEnabled = true
            settings.allowFileAccess = true // Still good to have
            settings.mediaPlaybackRequiresUserGesture = false
            
            // Basic optimization
            settings.cacheMode = WebSettings.LOAD_NO_CACHE
            
            webViewClient = object : WebViewClient() {
                override fun shouldInterceptRequest(
                    view: WebView,
                    request: WebResourceRequest
                ): WebResourceResponse? {
                    return assetLoader.shouldInterceptRequest(request.url)
                }
            }
            
            setBackgroundColor(android.graphics.Color.BLACK)
            
            // Load from the virtual domain
            // Note: Our assets are in 'assets/'. 
            // The AssetLoader maps "https://appassets.androidplatform.net/assets/" to the logical "assets" folder.
            // But verify: Standard assets are at root of assets/ dir.
            // Vite builds to 'assets/' folder INSIDE the APK assets?
            // Let's check:
            // S:\Source\Android\DaydreamClock\app\src\main\assets\index.html
            // S:\Source\Android\DaydreamClock\app\src\main\assets\assets\index-....js
            //
            // So requesting "https://appassets.androidplatform.net/assets/index.html" should map to 'index.html' in root?
            // "AssetsPathHandler(this)" maps to the root of the "assets" folder.
            // So "https://.../assets/index.html" -> assets/index.html. Correct.
            
            loadUrl("https://appassets.androidplatform.net/assets/index.html")
        }
    }
}
