package com.cooleshow.base.data.net;

import android.text.TextUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import okhttp3.HttpUrl;
import okhttp3.Request;

/**
 * Author by pq, Date on 2022/4/22.
 */
public class CommonParamsHelper {
    public static final String USER_TOKEN="Authorization";
    private volatile static CommonParamsHelper mInstance;
    private final Map<String, String> commonParams = new HashMap();
    private Map<String, String> commonHeaderParams = new HashMap();

    private CommonParamsHelper() {
    }

    public static CommonParamsHelper getInstance() {
        if (mInstance == null) {
            synchronized (CommonParamsHelper.class) {
                if (mInstance == null) {
                    mInstance = new CommonParamsHelper();
                }
            }
        }
        return mInstance;
    }

    public void addCommonParams(String key, String value) {
        if (TextUtils.isEmpty(key)) {
            return;
        }
        commonParams.put(key, value);
    }

    public synchronized void removeCommonParams(String key) {
        commonParams.remove(key);
    }

    public void addCommonHeaderParams(String key, String value) {
        if (TextUtils.isEmpty(key)) {
            return;
        }
        commonHeaderParams.put(key, value);
    }

    public synchronized void removeCommonHeaderParams(String key) {
        commonHeaderParams.remove(key);
    }

    public void clear() {
        if (commonHeaderParams != null) {
            commonHeaderParams.clear();
        }
        if (commonParams != null) {
            commonParams.clear();
        }
    }

    public Request.Builder insertCommonHeaderParams(Request.Builder builder) {
        if (commonHeaderParams != null && commonHeaderParams.size() > 0) {
            Set<Map.Entry<String, String>> entries = commonHeaderParams.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String key = entry.getKey();
                String value = entry.getValue();
                builder.header(key, value);
            }
        }
        return builder;
    }

    public HttpUrl.Builder insertCommonUrlParams(HttpUrl.Builder builder) {
        if (commonParams != null && commonParams.size() > 0) {
            Set<Map.Entry<String, String>> entries = commonParams.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String key = entry.getKey();
                String value = entry.getValue();
                builder.addQueryParameter(key, value);
            }
        }
        return builder;
    }

}
