package quant.rich.emoney.patch.okhttp;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Request;

public class RequestContext {
    public final Map<String, String> headers;
    public final String scheme;
    public final String host;
    public final Request.Builder builder;

    /**
     * 使用 OkHttp Request.Builder 来初始化上下文，包括 scheme、host 和 headers
     * @param builder
     */
    public RequestContext(Request.Builder builder) {
        this.builder = builder;
        List<String> nvList = builder.getHeaders$okhttp().getNamesAndValues$okhttp();

        Map<String, String> headerMap = new HashMap<>();
        for (int i = 0; i < nvList.size(); i += 2) {
            headerMap.put(nvList.get(i), nvList.get(i + 1));
        }
        this.headers = headerMap;
        
        String url = builder.getUrl$okhttp().toString();
        this.scheme = url.startsWith("https") ? "https" : "http";
        this.host = url.replaceFirst("https?://", "").split("/")[0];
    }
    
    /**
     * 使用指定 headers、scheme 和 host 来初始化上下文，一般用在单元测试场景
     * @param headers
     * @param scheme
     * @param host
     */
    public RequestContext(Map<String, String> headers, String scheme, String host) {
        this.builder = null;
        this.headers = headers;
        this.scheme = scheme;
        this.host = host;
    }
}