package com.tencent.qian.webview.scheme;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Supplier;

import com.tencent.qian.webview.model.SdkEvent;
import com.tencent.qian.webview.model.SignCallback;

import java.util.List;

/**
 * 外部 scheme（微信 / 支付宝 / 自定义）处理器。
 */
public final class ExternalSchemeHandler {

    private static final String TAG = "QianExternalScheme";

    private final List<String> externalSchemes;
    private final Supplier<SignCallback> callbackProvider;

    public ExternalSchemeHandler(@NonNull List<String> externalSchemes, @NonNull Supplier<SignCallback> callbackProvider) {
        this.externalSchemes = externalSchemes;
        this.callbackProvider = callbackProvider;
    }

    /**
     * 尝试启动外部 App。
     *
     * @return {@code true} 已识别，{@code false} 未识别
     */
    public boolean tryStartActivity(@NonNull Context context, @Nullable String urlString) {
        if (urlString == null || urlString.isEmpty()) return false;

        Uri uri;
        try {
            uri = Uri.parse(urlString);
        } catch (Exception e) {
            return false;
        }

        String scheme = uri.getScheme();
        if (scheme == null) return false;
        scheme = scheme.toLowerCase();

        // http(s) 不归本 handler 处理
        if ("http".equals(scheme) || "https".equals(scheme)) return false;
        // qianapp 优先级最高，不会走到这里；防御性兜底
        if ("qianapp".equals(scheme)) return false;

        boolean matched = false;
        for (String s : externalSchemes) {
            if (s.equalsIgnoreCase(scheme)) {
                matched = true;
                break;
            }
        }

        if (!matched) {
            SignCallback cb = callbackProvider.get();
            if (cb != null) cb.onEvent(new SdkEvent.SchemeNotMatched(urlString));
            return true;
        }

        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            SignCallback cb = callbackProvider.get();
            if (cb != null) cb.onEvent(new SdkEvent.SchemeIntercepted(scheme, urlString));
            return true;
        } catch (ActivityNotFoundException e) {
            Log.w(TAG, "no Activity for scheme=" + scheme + " url=" + urlString, e);
            SignCallback cb = callbackProvider.get();
            if (cb != null) cb.onEvent(new SdkEvent.SchemeNotMatched(urlString));
            return true;
        } catch (SecurityException e) {
            Log.w(TAG, "security denied scheme=" + scheme + " url=" + urlString, e);
            SignCallback cb = callbackProvider.get();
            if (cb != null) cb.onEvent(new SdkEvent.SchemeNotMatched(urlString));
            return true;
        }
    }
}
