package com.game.webgame.network;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import com.http.xml.callback.MyHttpCallBack;
import android.accounts.NetworkErrorException;
import android.os.AsyncTask;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/4/24.
 */

public class HttpUtil {
    private MyHttpCallBack callback;
    private String method;
    private Map<String, String> map;
    private String path;
    @SuppressWarnings(value = "deprecation")
    private static HttpClient client;

    private static OkHttpClient okHttpClient;


    public static HttpClient gethttp(){
        if(client==null){
            client=new  DefaultHttpClient();
        }

        return client;

    }
    public static OkHttpClient getOkHttpClientttp(){
        if(okHttpClient==null){
            okHttpClient=new  OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
        }

        return okHttpClient;

    }
    private HttpUtil() {
        // TODO Auto-generated constructor stub
    }

    public HttpUtil(MyHttpCallBack callback,String method,String path,Map<String,String> map) {
        this.callback = callback;
        this.method = method;
        this.path = path;
        this.map = map;
    }

    public void startRequest(){
        HttpAsyncTask task = new HttpAsyncTask();
        task.execute();
    }

    /**
     * http网络请求，
     * 两种方式：GET/POST
     * 方法：很多，1）原生的请求,androidsdk自带的java网络请求类--HttpUrlConnection；
     * 2）第三方封装的请求：HttpClient(android自带的); NoHttp;volley;OkHttp;XUtil;
     * @throws Exception
     */

    public String doGetByHttpUrlConnection(String path,Map<String,String> map) throws Exception{
        String params = getParamsFromMap(map);
        path = path + "?"+params;
        URL url = new URL(path);
        //打开连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置连接超时时间
        conn.setConnectTimeout(5000);
        //设置请求方式
        conn.setRequestMethod("GET");
        //判断是否能够连接成功--响应码(200成功；300没有权限;400没有资源--可能是路径不对；
        //500服务器内部错误----一般是传参名字或者类型出错了or是服务器本身报错)
        int responseCode = conn.getResponseCode();
        System.out.println("responseCode:"+responseCode);
        if(responseCode==200){//ok
            InputStream is = conn.getInputStream();
            String result = getStringFromStream(is);
            return result;
        }else{//连接出错
            throw  new NetworkErrorException();
        }
    }

    private String getStringFromStream(InputStream is) throws Exception{
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while((len = is.read(buffer))!=-1){
            baos.write(buffer, 0, len);
        }
        String result = baos.toString();
        baos.close();
        is.close();
        return result;
    }

    public String doPostByHttpUrlConnection(String path,Map<String,String> map) throws Exception{
        URL url = new URL(path);
        //打开连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置连接超时时间
        conn.setConnectTimeout(5000);
        //设置请求方式
        conn.setRequestMethod("POST");
        //将参数一起通过post方式传过去，然后再拿响应
        OutputStream os = conn.getOutputStream();
        //username=yolanda&pwd=nohttp
        String params = getParamsFromMap(map);
        os.write(params.getBytes());
        int responseCode = conn.getResponseCode();
        System.out.println("responseCode:"+responseCode);
        if(responseCode==200){//ok
            InputStream is = conn.getInputStream();
            String result = getStringFromStream(is);
            return result;
        }else{//连接出错
            throw  new NetworkErrorException();
        }
    }

    private String getParamsFromMap(Map<String,String> map){
        StringBuffer buffer = new StringBuffer();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            buffer.append(key).append("=").append(value).append("&");
        }
        buffer.deleteCharAt(buffer.length()-1);
        return buffer.toString();
    }

    /**
     * 第二种方式 HTTPCLIENT
     * @return
     * @throws Exception
     * @throws ClientProtocolException
     */

    @SuppressWarnings("deprecation")
    public String doGetByHttpClient(String path,Map<String,String> map) throws ClientProtocolException, Exception{
        if(map!=null){
            String params = getParamsFromMap(map);
            System.out.println("path:"+path);
            path = path + "?"+params;
        }
        System.out.println(path);
        //得到一个get请求
        HttpGet get = new HttpGet(path);
        //得到一个http请求客户端
        HttpClient client =new DefaultHttpClient();
        //设置请求超时时间5s
        get.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
        HttpResponse response = client.execute(get);
        System.out.println("-----"+path);
        //状态码--响应码
        int statusCode = response.getStatusLine().getStatusCode();

        System.out.println(statusCode);

        if(statusCode==200){//ok
//			InputStream is = response.getEntity().getContent();
//			String result = getStringFromStream(is);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            System.out.println(result);
            return result;
        }else{//连接出错
            throw  new NetworkErrorException();
        }
    }

    @SuppressWarnings("deprecation")
    public String doPostByHttpClient(String path,Map<String,String> map) throws Exception{
        //得到一个http请求客户端

        HttpClient client = gethttp();

        HttpPost post = new HttpPost(path);
        //设置post请求参数
        List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            BasicNameValuePair pair = new BasicNameValuePair(key, value);
            parameters.add(pair );
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        //状态码--响应码
        int statusCode = response.getStatusLine().getStatusCode();
        if(statusCode==200){//ok
//			InputStream is = response.getEntity().getContent();
//			String result = getStringFromStream(is);

            HttpEntity responseEntity = response.getEntity();
            String result = EntityUtils.toString(responseEntity);
            return result;
        }else{//连接出错
            throw  new NetworkErrorException();
        }
    }

    public String doPostByOkHttpClient(String path,Map<String,String> map) throws Exception{
        //得到一个http请求客户端

        OkHttpClient client = getOkHttpClientttp();

//        HttpPost post = new HttpPost(path);
        FormBody.Builder builder = new FormBody.Builder();
//        FormBody body = new FormBody.Builder();
        //设置post请求参数
        List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            BasicNameValuePair pair = new BasicNameValuePair(key, value);
            parameters.add(pair );
            builder.add(key,value);
        }
        RequestBody requestBodyPost = builder.build();
        Request requestPost = new Request.Builder()
                .url(path)
                .post(requestBodyPost)
                .build();
//        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
//        post.setEntity(entity);
//        HttpResponse response = client.execute(post);
        Call call = client.newCall(requestPost);
        Response response = call.execute();
        //状态码--响应码
//        int statusCode = response.getStatusLine().getStatusCode();
        int statusCode = response.code();
        if(statusCode==200){//ok
//			InputStream is = response.getEntity().getContent();
//			String result = getStringFromStream(is);

//            HttpEntity responseEntity = response.getEntity();
//            String result = EntityUtils.toString(responseEntity);
            return response.body().string();
        }else{//连接出错
            throw  new NetworkErrorException();
        }
    }
    class HttpAsyncTask extends AsyncTask<Void, Void, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            //登陆
            try {

                String result = null;
                if("GET".equals(method)){
                    System.out.println("path:"+path);
                    result = doGetByHttpClient(path, map);
                }else{
//                    Ayni OkHttp doPostByOkHttpClient
//                    result = doPostByHttpClient(path, map);
                    result = doPostByOkHttpClient(path, map);

                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if(result!=null){
                if("failed".equals(result)){
                    callback.failed(result);
                }else{
                    callback.success(result);
                }
            }
        }

    }
}
