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:
 *
 * <ul>
 *   <li>自带一个空 WebView</li>
 *   <li>{@code onCreate} 内调 {@link TencentQianWebViewConfigurator#apply} 套用 SDK 全部能力</li>
 *   <li>然后 {@code loadUrl} 加载主页传过来的 URL</li>
 * </ul>
 *
 * 演示客户「已有自有 WebView 容器,只想接入 SDK 的能力」的场景。
 */
public class ConfiguratorDemoActivity extends AppCompatActivity {

    private static final String EXTRA_URL = "url";

    private static volatile SignCallback pendingCallback;

    private WebView webView;
    private TencentQianWebViewConfigurator.Handle handle;

    /**
     * 启动 ConfiguratorDemoActivity。
     *
     * @param from     发起 Activity
     * @param url      要加载的签署 URL
     * @param callback 签署回调(通过 volatile 静态字段传递,避免序列化)
     */
    public static void start(Activity from, String url, SignCallback callback) {
        pendingCallback = callback;
        Intent intent = new Intent(from, ConfiguratorDemoActivity.class);
        intent.putExtra(EXTRA_URL, url);
        from.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 传统模式：系统自动处理 insets，adjustResize 正常生效
        WindowCompat.setDecorFitsSystemWindows(getWindow(), true);
        setContentView(R.layout.activity_configurator_demo);

        webView = findViewById(R.id.demo_webview);

        String url = getIntent() != null ? getIntent().getStringExtra(EXTRA_URL) : "";
        if (url == null) url = "";

        SignCallback cb = pendingCallback;
        pendingCallback = null;

        handle = TencentQianWebViewConfigurator.apply(
                this,
                webView,
                new TencentQianWebViewConfig.Builder()
                        .userAgentExtra("qianwv-demo/1.0.0(configurator)")
                        .build(),
                cb
        );

        if (!url.isEmpty()) {
            webView.loadUrl(url);
        }
    }

    @Override
    protected void onDestroy() {
        if (handle != null) {
            handle.detachAndDestroy();
        }
        super.onDestroy();
    }
}
