package com.tencent.qian.webview.internal;

import android.annotation.SuppressLint;
import android.os.Build;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;

import androidx.annotation.NonNull;

import com.tencent.qian.webview.TencentQianWebView;
import com.tencent.qian.webview.model.TencentQianWebViewConfig;

/**
 * DOM Storage + Cookie + 第三方 Cookie + 标准 WebSettings 套用工具。
 */
@SuppressWarnings("deprecation")
public final class WebSettingsApplier {

    private WebSettingsApplier() {}

    @SuppressLint("SetJavaScriptEnabled")
    public static void apply(@NonNull WebView webView, @NonNull TencentQianWebViewConfig config) {
        WebSettings s = webView.getSettings();

        // ────────── DOM Storage + Cookie + 第三方 Cookie ──────────
        s.setJavaScriptEnabled(true);
        s.setDomStorageEnabled(true);
        CookieManager cm = CookieManager.getInstance();
        cm.setAcceptCookie(true);
        cm.setAcceptThirdPartyCookies(webView, true);

        // ────────── 内容混合 ──────────
        switch (config.getAllowMixedContent()) {
            case NEVER:
                s.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
                break;
            case ALWAYS:
                s.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
                break;
            case COMPATIBILITY:
            default:
                s.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
                break;
        }

        // ────────── 视图缩放 ──────────
        s.setUseWideViewPort(true);
        s.setLoadWithOverviewMode(true);
        s.setTextZoom(100);
        s.setSupportZoom(true);
        s.setBuiltInZoomControls(true);
        s.setDisplayZoomControls(false);

        // ────────── 文件 / 媒体 ──────────
        s.setAllowFileAccess(false);
        s.setAllowContentAccess(false);
        s.setMediaPlaybackRequiresUserGesture(false);

        // ────────── 弹窗 / 多窗口 ──────────
        s.setJavaScriptCanOpenWindowsAutomatically(false);
        s.setSupportMultipleWindows(false);

        // ────────── 缓存 ──────────
        s.setCacheMode(WebSettings.LOAD_DEFAULT);

        // ────────── 字体编码 ──────────
        s.setDefaultTextEncodingName("UTF-8");

        // ────────── 渲染优先级 ──────────
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            s.setRenderPriority(WebSettings.RenderPriority.HIGH);
        }

        // ────────── User-Agent ──────────
        if (config.isInjectUserAgent()) {
            String systemUa = s.getUserAgentString();
            s.setUserAgentString(buildUserAgent(systemUa != null ? systemUa : "", config.getUserAgentExtra()));
        }
    }

    @NonNull
    public static String buildUserAgent(@NonNull String systemUa, @NonNull String userAgentExtra) {
        StringBuilder sb = new StringBuilder(systemUa.trim());
        if (sb.length() > 0) sb.append(' ');
        sb.append("qianwv/").append(TencentQianWebView.sdkVersion());
        if (userAgentExtra != null && !userAgentExtra.trim().isEmpty()) {
            sb.append(' ').append(userAgentExtra.trim());
        }
        return sb.toString();
    }
}
