package com.tencent.qian.webview.scheme;

import android.os.Handler;
import android.os.Looper;

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 com.tencent.qian.webview.model.SignResult;

/**
 * {@code qianapp://} scheme 拦截器。
 */
public final class SchemeInterceptor {

    private final Supplier<SignCallback> callbackProvider;
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    public SchemeInterceptor(@NonNull Supplier<SignCallback> callbackProvider) {
        this.callbackProvider = callbackProvider;
    }

    /**
     * 尝试拦截 URL。
     *
     * @return {@code true} 已识别并处理，{@code false} 未识别
     */
    public boolean handle(@Nullable String url) {
        if (!SignResultParser.isQianAppScheme(url)) return false;

        SignResult result = SignResultParser.parse(url);
        SignCallback cb = callbackProvider.get();

        String finalUrl = url != null ? url : "";
        dispatchOnMain(() -> {
            if (cb != null) {
                cb.onSignResult(result);
                cb.onEvent(new SdkEvent.SchemeIntercepted("qianapp", finalUrl));
            }
        });
        return true;
    }

    private void dispatchOnMain(@NonNull Runnable block) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            block.run();
        } else {
            mainHandler.post(block);
        }
    }
}
