package com.wechat.common.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

import net.sf.json.JSONObject;

public class NetworkUtils extends BaseUtils{

    /**
     * 通过HTTP Post请求外部数据
     * @param url 要访问的地址
     * @param request 发送的数据， 会被转换成json字符串
     * @param classofResp 返回数据类的类型
     * @param <T> 返回数据类
     * @return 将远端返回的Json字串解析为对象，类型为T
     */
    public static <T> T getRemoteResponseAsJson(String url, Object request, Class<T> classofResp) {
        String payload = JacksonUtils.bean2json(request);
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");

            // Send post request
            con.setDoOutput(true);
            PrintWriter wr = new PrintWriter(new OutputStreamWriter(
            		con.getOutputStream(), "UTF-8"));
            wr.write(payload);
            wr.flush();
            wr.close();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            log.debug("Get response: " + response.toString());
            return JacksonUtils.deserialize(response.toString(), classofResp);
            
        } catch (Exception ex) {
            log.error("Network error.", ex);
            return null;
        }
    }

    /**
     * 通过HTTP Post请求外部数据
     * @param url 要访问的地址
     * @param request 发送的数据， 会被转换成json字符串
     * @param classofResp 返回数据类的类型
     * @return 将远端返回的Json字串解析为对象，类型为T
     */
    public static String getResponseAsApp(String url, Object request) {
        String payload = JacksonUtils.bean2json(request);
        try {
        	
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");

            // Send post request
            con.setDoOutput(true);
            PrintWriter wr = new PrintWriter(new OutputStreamWriter(
            		con.getOutputStream(), "UTF-8"));
            wr.write(payload);
            wr.flush();
            wr.close();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            log.debug("Get response: " + response.toString());
            return response.toString();
            
        } catch (Exception ex) {
            log.error("Network error.", ex);
            return null;
        }
    }
    
    
    /**
     * 通过HTTP Post请求外部数据
     * @param url 要访问的地址
     * @param request 发送的数据， 会被转换成json字符串
     * @param classofResp 返回数据类的类型
     * @return 将远端返回的Json字串解析为对象，类型为T
     */
    public static String getRemoteResponseAsJson(String url, Object request) {
        String payload = JacksonUtils.bean2json(request);
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");

            // Send post request
            con.setDoOutput(true);
            PrintWriter wr = new PrintWriter(new OutputStreamWriter(
            		con.getOutputStream(), "UTF-8"));
            wr.write(payload);
            wr.flush();
            wr.close();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            log.debug("Get response: " + response.toString());
            return response.toString();
            
        } catch (Exception ex) {
            log.error("Network error.", ex);
            return null;
        }
    }
    
    public static <T> T getRemoteResponseAsJsonWithStringPayload(String url, String req, Class<T> classofResp){
        String payload = req;
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");

            // Send post request
            con.setDoOutput(true);
            PrintWriter wr = new PrintWriter(new OutputStreamWriter(
            		con.getOutputStream(), "UTF-8"));
            wr.write(payload);
            wr.flush();
            wr.close();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            log.debug("Get response: " + response.toString());
            return JacksonUtils.deserialize(response.toString(), classofResp);

        } catch (Exception ex) {
            log.error("Network error.", ex);
            return null;
        }
    }
    
    
    /**
     * 通过HTTP Get请求外部数据,以JSON格式直接返回
     * @param url 要访问的地址
     * @param request 发送的数据， 会被转换成JSON字符串
     * @param 以JSON格式直接返回
     * @return 将远端返回的JSON字串
     */
    public static JSONObject getRemoteResponseAsJson(String url) {
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("GET");
            con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");

            // Send post request
            con.setDoOutput(true);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            log.debug("Get response: " + response.toString());
            return JacksonUtils.StringTOJson(response.toString());
            
        } catch (Exception ex) {
            log.error("Network error.", ex);
            return null;
        }
    }
    
    /**
       * 通过HTTP Get请求外部数据,以JSON格式直接返回
     * @param url 要访问的地址
     * @param classofResp需要格式化的目标类型
     * @return 将远端返回的JSON格式化后输出
     */
    public static <T> T getRemoteResponseAsClass(String url, Class<T> classofResp) {
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("GET");
			con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");

            // Send post request
            con.setDoOutput(true);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            log.debug("Get response: " + response.toString());
            return JacksonUtils.deserialize(response.toString(), classofResp);
            
        } catch (Exception ex) {
            log.error("Network error.", ex);
            return null;
        }
    }


    /**
     * 通过HTTP Get请求外部数据,以JSON格式直接返回
   * @param url 要访问的地址
   * @param classofResp需要格式化的目标类型
   * @return 将远端返回的JSON格式化后输出
   */
/*    public static <T> T getRemoteResponseAsJsonMethodGET(String url, Class<T> classofResp){
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("GET");
            con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");

            con.setDoOutput(false);
            con.setDoInput(true);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            log.debug("Get response: " + response.toString());
            return JacksonUtils.deserialize(response.toString(), classofResp);

        } catch (Exception ex) {
            log.error("Network error.", ex);
            return null;
        }
    }*/
}
