package com.tencent.qian.webview.demo

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.webkit.WebView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import com.tencent.qian.webview.TencentQianWebViewConfigurator
import com.tencent.qian.webview.model.SignCallback
import com.tencent.qian.webview.model.TencentQianWebViewConfig

/**
 * 配置模式 Demo:
 *
 * - 自带一个空 WebView
 * - `onCreate` 内调 [TencentQianWebViewConfigurator.apply] 套用 SDK 全部能力
 * - 然后 `loadUrl` 加载主页传过来的 URL
 *
 * 演示客户「已有自有 WebView 容器,只想接入 SDK 的能力」的场景。
 */
class ConfiguratorDemoActivity : AppCompatActivity() {

    private lateinit var webView: WebView
    private var handle: TencentQianWebViewConfigurator.Handle? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 传统模式：系统自动处理 insets，adjustResize 正常生效
        WindowCompat.setDecorFitsSystemWindows(window, true)
        setContentView(R.layout.activity_configurator_demo)

        webView = findViewById(R.id.demo_webview)

        val url = intent?.getStringExtra(EXTRA_URL).orEmpty()
        val cb = pendingCallback
        pendingCallback = null

        handle = TencentQianWebViewConfigurator.apply(
            activity = this,
            webView = webView,
            config = TencentQianWebViewConfig(
                userAgentExtra = "qianwv-demo/1.0.0(configurator)"
            ),
            callback = cb
        )

        if (url.isNotEmpty()) webView.loadUrl(url)
    }

    override fun onDestroy() {
        handle?.detachAndDestroy()
        super.onDestroy()
    }

    companion object {
        private const val EXTRA_URL = "url"

        @Volatile
        private var pendingCallback: SignCallback? = null

        fun start(from: Activity, url: String, callback: SignCallback?) {
            pendingCallback = callback
            val intent = Intent(from, ConfiguratorDemoActivity::class.java)
                .putExtra(EXTRA_URL, url)
            from.startActivity(intent)
        }
    }
}
