package cn.com.ctop.crawler.modules.core.util;

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

public class HttpParamUtil {
    public static <K, V> String mapToString(Map<K, V> map, List<String> ignoreKeyList){
        if (map == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        try{
            for(K key :map.keySet()){
                if(ignoreKeyList!=null && ignoreKeyList.contains(key)){
                    continue;
                }
                sb.append(key + "=" + URLDecoder.decode(String.valueOf(map.get(key)), "UTF-8"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static <K, V> String mapToUrlString(Map<K, V> map, List<String> ignoreKeyList){
        if (map == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        try{
            for(K key :map.keySet()){
                if(ignoreKeyList!=null && ignoreKeyList.contains(key)){
                    continue;
                }
                sb.append("&"+key + "=" + URLDecoder.decode(String.valueOf(map.get(key)==null?"":map.get(key)), "UTF-8"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sb.toString().substring(1);
    }

    public static <K, V> String mapToUrlStringNoEncoder(Map<K, V> map, List<String> ignoreKeyList){
        if (map == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        try{
            for(K key :map.keySet()){
                if(ignoreKeyList!=null && ignoreKeyList.contains(key)){
                    continue;
                }
                sb.append("&"+key + "=" + String.valueOf(map.get(key)==null?"":map.get(key)));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sb.toString().substring(1);
    }

    public static Map<String,String> urlParamToMap(String urlParam){
        if (urlParam == null || "".equalsIgnoreCase(urlParam)) {
            return null;
        }
        String[] arr = urlParam.split("\\&");
        Map<String,String> map = new HashMap<String,String>();
        for (String item : arr) {
            String[] itemArr = item.split("=", 2);
            map.put(itemArr[0], itemArr[1]);
        }
        return map;
    }
}
