/**
 * Cobub Razor
 * <p/>
 * An open source analytics android sdk for mobile applications
 *
 * @package Cobub Razor
 * @author WBTECH Dev Team
 * @copyright Copyright (c) 2011 - 2012, NanJing Western Bridge Co.,Ltd.
 * @license http://www.cobub.com/products/cobub-razor/license
 * @link http://www.cobub.com/products/cobub-razor/
 * @filesource
 * @since Version 0.1
 */
package com.oo.seex.oo_statistics_lib.network;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.oo.seex.oo_statistics_lib.utils.CommonUtil;

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


/**
 * @author dance
 *         处理与服务器交互的操作  使用的时httpclient     传入url以及要传递的数据就可以请求服务器了
 */
public class NetworkUitlity {

    private static final String TAG = "network";

    private static NetworkUitlity sUitlity = new NetworkUitlity();

    private NetworkUitlity(){

    }

    public static NetworkUitlity getInstance(){
        return sUitlity;
    }


    public void requestPost(String baseUrl,HashMap<String, String> paramsMap,Context context,NetListener listener) {
        try {
            if(!TextUtils.isEmpty(baseUrl)){
                Log.i("数据上传","url:"+baseUrl);
                if(baseUrl.contains("https")){
                    requestHttpsPost(baseUrl,paramsMap,context,listener);
                }else{
                    requestHttpPost(baseUrl,paramsMap,context,listener);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if(listener != null){
                listener.error();
            }
        }
    }

    private void requestHttpPost(String baseUrl,HashMap<String, String> paramsMap,Context context,NetListener listener) {
        try {
            if(paramsMap == null || paramsMap.size() == 0){
                listener.error();
                return;
            }
            //合成参数
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key,  URLEncoder.encode(paramsMap.get(key),"utf-8")));
                pos++;
            }
            String params =tempParams.toString();
            // 请求的参数转换为byte数组
            byte[] postData = params.getBytes();
            // 新建一个URL对象
            URL url = new URL(baseUrl);
            // 打开一个HttpURLConnection连接
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

            // 设置连接超时时间
            urlConn.setConnectTimeout(30 * 1000);
            //设置从主机读取数据超时
            urlConn.setReadTimeout(30 * 1000);
            // Post请求不能使用缓存
            urlConn.setUseCaches(false);
            // 设置为Post请求
            urlConn.setRequestMethod("POST");
            //设置本次连接是否自动处理重定向
            urlConn.setInstanceFollowRedirects(true);
            // 配置请求Content-Type
            urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            StringBuilder user_agent = new StringBuilder();
            user_agent.append("device_sn:" + Build.SERIAL);
            user_agent.append(";user_id:" + CommonUtil.getUserIdentifier(context));
            user_agent.append(";device_ip:" + CommonUtil.getIp(context));
            user_agent.append(";os_version:" + CommonUtil.getOSVersion(context));
            user_agent.append(";soft_version:" + CommonUtil.getVersion(context));
            user_agent.append(";app_key:" + CommonUtil.getAppKey(context));
            user_agent.append(";platform:" + Build.PRODUCT);
            Log.e("requestHttpPost","baseUrl:"+baseUrl);
            Log.e("requestHttpPost","user_agent:"+user_agent.toString());
            urlConn.setRequestProperty("User-Agent", user_agent.toString());

            // 开始连接
            urlConn.connect();
            // 发送请求参数
            DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
            dos.write(postData);
            dos.flush();
            dos.close();
            // 判断请求是否成功
            if (urlConn.getResponseCode() == 200) {
                if(listener != null){
                    listener.succee();
                }
                Log.e(TAG, "数据上传成功成功: "+baseUrl);
            } else {
                if(listener != null){
                    listener.error();
                }
                Log.e(TAG, "数据上传失败失败："+urlConn.getResponseCode() +"baseUrl"+baseUrl);
            }
            // 关闭连接
            urlConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            if(listener != null){
                listener.error();
            }
        }
    }
    private void requestHttpsPost(String baseUrl,HashMap<String, String> paramsMap,Context context,NetListener listener) {
        try {
            if(paramsMap == null || paramsMap.size() == 0){
                listener.error();
                return;
            }
            //合成参数
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key,  URLEncoder.encode(paramsMap.get(key),"utf-8")));
                pos++;
            }
            String params =tempParams.toString();
            // 请求的参数转换为byte数组
            byte[] postData = params.getBytes();
            // 新建一个URL对象
            URL url = new URL(baseUrl);
            // 打开一个HttpURLConnection连接
            HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();

            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }};

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            urlConn.setSSLSocketFactory(sslContext.getSocketFactory());
            urlConn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });

            // 设置连接超时时间
            urlConn.setConnectTimeout(30 * 1000);
            //设置从主机读取数据超时
            urlConn.setReadTimeout(30 * 1000);
            // Post请求不能使用缓存
            urlConn.setUseCaches(false);
            // 设置为Post请求
            urlConn.setRequestMethod("POST");
            //设置本次连接是否自动处理重定向
            urlConn.setInstanceFollowRedirects(true);
            // 配置请求Content-Type
            urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            StringBuilder user_agent = new StringBuilder();
            user_agent.append("device_sn:" + Build.SERIAL);
            user_agent.append(";user_id:" + CommonUtil.getUserIdentifier(context));
            user_agent.append(";device_ip:" + CommonUtil.getIp(context));
            user_agent.append(";os_version:" + CommonUtil.getOSVersion(context));
            user_agent.append(";soft_version:" + CommonUtil.getVersion(context));
            user_agent.append(";app_key:" + CommonUtil.getAppKey(context));
            user_agent.append(";platform:" + Build.PRODUCT);
            Log.e("requestHttpsPost","baseUrl:"+baseUrl);
            Log.e("requestHttpsPost","user_agent:"+user_agent.toString());
            urlConn.setRequestProperty("User-Agent", user_agent.toString());

            // 开始连接
            urlConn.connect();
            // 发送请求参数
            DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
            dos.write(postData);
            dos.flush();
            dos.close();
            // 判断请求是否成功
            if (urlConn.getResponseCode() == 200) {
                if(listener != null){
                    listener.succee();
                }
                Log.e(TAG, "数据上传成功成功: "+baseUrl);
            } else {
                if(listener != null){
                    listener.error();
                }
                Log.e(TAG, "数据上传失败失败："+urlConn.getResponseCode() +"baseUrl"+baseUrl);
            }
            // 关闭连接
            urlConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            if(listener != null){
                listener.error();
            }
        }
    }

    public interface NetListener{
        public void succee();
        public void error();
    }

}
