package com.ahau.againstpest.HttpProcessor;

import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 注释:代理模式的代理
 *
 * @author fanchunchun
 * @date 2018/4/3
 */

public class HttpHelper implements IHttpProcessor{
    private static IHttpProcessor mIHttpProcessor = null;
    private Map<String, Object> mParams;
    private static HttpHelper _instance;

    private HttpHelper() {
        mParams = new HashMap<>();
    }


    /**
     * 单例设计模式
     * @return
     */
    public static  HttpHelper obtain() {
        synchronized (HttpHelper.class) {
            if (_instance == null) {
                _instance = new HttpHelper();
            }
        }
        return _instance;
    }

    public static void  init(IHttpProcessor httpProcessor) {
        mIHttpProcessor = httpProcessor;
    }

    @Override
    public void post(String url, Map<String, Object> params, ICallback callback) {
        final String finalUrl = appendParams(url, params);
        mIHttpProcessor.post(finalUrl, params,callback);
    }

    @Override
    public void get(String url, Map<String, Object> params, ICallback callback) {
        final String finalUrl = appendParams(url, params);
        mIHttpProcessor.get(finalUrl, params, callback);
    }

    private String appendParams(String url, Map<String, Object> params) {
        if (params == null || params.isEmpty()) {
            return url;
        }

        StringBuilder urlBuilder = new StringBuilder(url);
        if (urlBuilder.indexOf("?")<= 0) {
            urlBuilder.append("?");
        }else {
            if (!urlBuilder.toString().endsWith("?")) {
                urlBuilder.append("&");
            }
        }
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            urlBuilder.append(entry.getKey()).append("=").append(encode(entry.getValue().toString()));
        }
        return urlBuilder.toString();
    }

    //URI不允许有空格等字符，如果参数值有空格，需要此方法转换
    private static String encode(String str) {
        try {
            return URLEncoder.encode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            //针对不支持的编码时报错，utf-8应该是支持的
            Log.e("参数转码异常", e.toString());
            throw new RuntimeException(e);
        }
    }
}
