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 Map<String, String> headers;
    public String scheme = null;
    public String host = null;
    public String url = null;

    /**
     * 使用 OkHttp Request.Builder 来初始化上下文
     * @param builder
     */
    public RequestContext(Request.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;
        
        if (builder.getUrl$okhttp() != null) {
            String url = builder.getUrl$okhttp().toString();
            this.scheme = url.startsWith("https") ? "https" : "http";
            this.host = url.replaceFirst("https?://", "").split("/")[0];
            this.url = url;
        }
    }
    

    /**
     * 使用 OkHttp Request 来初始化上下文
     * @param builder
     */
    public RequestContext(Request request) {
        this(request.newBuilder());
    }
}