package dev.yuzu.gca

import android.os.Bundle
import android.util.Log
import android.webkit.WebView
import androidx.appcompat.app.AppCompatActivity
import java.io.File

class MainActivity : AppCompatActivity() {

    private val cacheFile: File by lazy { File(filesDir, "gca_hot.html") }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val wv = WebView(this).apply {
            if (0 != (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE)) {
                WebView.setWebContentsDebuggingEnabled(true)
            }
            settings.javaScriptEnabled = true
            settings.domStorageEnabled = true
            settings.allowFileAccess = true
            settings.allowFileAccessFromFileURLs = true
            settings.allowUniversalAccessFromFileURLs = true
            settings.mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            addJavascriptInterface(Bridge(this@MainActivity), "Android")

            if (cacheFile.exists()) {
                val html = cacheFile.readText()
                loadDataWithBaseURL("https://gca.app/", html, "text/html", "UTF-8", null)
                Log.i(TAG, "Loaded cached HTML (${cacheFile.length()}B)")
            } else {
                loadUrl("file:///android_asset/index.html")
                Log.i(TAG, "Loaded embedded index.html")
            }
        }
        setContentView(wv)
    }

    inner class Bridge(private val ctx: MainActivity) {
        @android.webkit.JavascriptInterface
        fun saveCache(html: String) {
            ctx.cacheFile.writeText(html)
            Log.i(TAG, "Hot-update HTML saved (${html.length}B)")
        }
        @android.webkit.JavascriptInterface
        fun clearCache() {
            ctx.cacheFile.delete()
            Log.i(TAG, "Cache cleared")
        }
    }

    companion object { private const val TAG = "GCA-H5" }
}
