package cn.edu.tju.se.base.web;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.IOUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.edu.tju.se.base.domain.Dict;
import cn.edu.tju.se.base.domain.DictValue;

public class HttpClient {
	public static String doHttpGet(String url) {
		StringBuilder json = new StringBuilder();
		try {
			URL urlObject = new URL(url);
			URLConnection uc = urlObject.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					uc.getInputStream()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
			}
			in.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json.toString();
	}

	public static String doHttpPost(String postData, String URL) {
		// System.out.println("发起的数据:"+postData);
		byte[] bytePostData = postData.getBytes();
		InputStream instr = null;
		//java.io.ByteArrayOutputStream out = null;
		try {
			URL url = new URL(URL);
			URLConnection urlCon = url.openConnection();
			urlCon.setDoOutput(true);
			urlCon.setDoInput(true);
			urlCon.setUseCaches(false);
			urlCon.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded; charset=UTF-8");
			urlCon.setRequestProperty("Content-length",
					String.valueOf(bytePostData.length));
			DataOutputStream printout = new DataOutputStream(
					urlCon.getOutputStream());
			printout.write(bytePostData);
			printout.flush();
			printout.close();
			instr = urlCon.getInputStream();
			byte[] bis = IOUtils.toByteArray(instr);
			String ResponseString = new String(bis, "UTF-8");
			if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
				System.out.println("返回空");
			}
			//System.out.println("返回数据为:" + ResponseString);
			return ResponseString;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				//out.close();
				instr.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return null;
	}

	public static List<Dict> jsonToList (String json,Dict template){
		ObjectMapper objectMapper = new ObjectMapper();
		List<Dict> result = new ArrayList<Dict>();
		try {
			List<LinkedHashMap<String, Object>> list = objectMapper.readValue(
					json, List.class);
			//System.out.println(list.size());
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = list.get(i);
				Set<String> set = map.keySet();
				Dict dict = new Dict();
				dict.setType(template.getType());
				String keyword = null;
				if (dict.getType().equalsIgnoreCase("province")){
					keyword = "shengji";
				} else if (dict.getType().equalsIgnoreCase("city")){
					keyword = "diji";
				}  else if (dict.getType().equalsIgnoreCase("district")){
					keyword = "xianji";
				}
				for (Iterator<String> it = set.iterator(); it.hasNext();) {
					String key = it.next();
					if (key.equalsIgnoreCase(keyword)) {
						List<DictValue> dictValues = new ArrayList<DictValue>(); 
						DictValue value = new DictValue();
						value.setLanguage("zh_CN");
						value.setValue(map.get(key).toString());
						dictValues.add(value);
						dict.setValues(dictValues);
						// System.out.println(key + ":" + map.get(key));
					} else if (key.equalsIgnoreCase("quHuaDaiMa")) {
						dict.setCode(map.get(key).toString());
					}
				}
				result.add(dict);
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}
