package com.imofan.android.develop.sns;

import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.util.List;
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.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.ConnectivityManager;
/***
 * SNS网络操作工具类
 * @author poble
 *
 */
public class MFSnsHttpUtil {
    // 网络超时设置
    public static int CONNECT_TIMEOUT = 20;
    public static int DATA_TIMEOUT = 40;
    
    /**
     * 获取当前网络状态(是否可用)
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context){
        boolean netWorkStatus = false;
        
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if(connManager.getActiveNetworkInfo()!=null){
            netWorkStatus = connManager.getActiveNetworkInfo().isAvailable();
        }
        return netWorkStatus;
    }

    /**
     * get方式，发送服务器请求
     * @param url
     * @param queryString
     * @return
     * @throws Exception
     */
    static String httpGet(String url, String queryString)
            throws Exception {
        String responseData = null;

        if (queryString != null && !queryString.equals("")) {
            url += "?" + queryString;
        }
        System.out.println(url);
        HttpGet method = new HttpGet(url);
        HttpClient httpClient = getNewHttpClient();
        try {
            HttpResponse response = httpClient.execute(method);
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK){
                responseData = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient = null;
        }
        return responseData;
    }
    /**
     * 下载图片
     * @param url 图片url地址
     * @return
     * @throws Exception
     */
    static InputStream download(String url)throws Exception {
        InputStream responseData = null;
        HttpGet method = new HttpGet(url);
        HttpClient httpClient = getNewHttpClient();
        try {
            HttpResponse response = httpClient.execute(method);
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK){
                responseData = response.getEntity().getContent();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient = null;
        }
        return responseData;
    }

    /**
     * post方式向服务器发送请求
     * 
     * @param url
     * @param params
     * @return
     */
   public static String httpPost(String url, List<NameValuePair> params) {
        String responseData = null;
        HttpResponse response=null;
        try {
            HttpClient httpClient = getNewHttpClient();
            HttpPost request = new HttpPost(url);
            if (params != null && params.size() > 0) {
                request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            }
            request.addHeader("User-Agent", "Android Multipart HTTP Client 1.0");
            HttpParams config = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(config,
                    CONNECT_TIMEOUT * 1000);
            HttpConnectionParams.setSoTimeout(config, DATA_TIMEOUT * 1000);

            response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                responseData = EntityUtils.toString(response.getEntity(),
                        "UTF-8");
            }else{
                responseData = "{'error_code':'"+response.getStatusLine().getStatusCode()+"'}";
            }
        } catch (Exception e) {
            responseData = "{'error_code':'500'}";
            e.printStackTrace();
        }
        
        return responseData;
    }

    /**
     * post方式向服务器发送请求，并上传图片
     * 
     * @param url
     * @param params
     * @param file
     * @return
     */
    static String httpPostWithPic(String url,
            List<NameValuePair> params, File file) {
        String responseData = null;
        try {
            HttpClient httpClient = getNewHttpClient();
            HttpPost request = new HttpPost(url);
            if (file != null && file.isFile() && file.exists()) {
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                entity.addPart("pic", new FileBody(file,"image/jpeg,image/png,image/gif"));
                if (params != null) {
                    for (NameValuePair param : params) {
                        entity.addPart(param.getName(),
                                new StringBody(param.getValue(),Charset.forName("UTF-8")));
                    }
                }
                request.setEntity(entity);
           }
            request.addHeader("User-Agent", "Android Multipart HTTP Client 1.0");
            request.addHeader("enctype", "multipart/form-data");
            HttpParams config = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(config,
                    CONNECT_TIMEOUT * 1000);
            HttpConnectionParams.setSoTimeout(config, DATA_TIMEOUT * 1000);
            HttpResponse response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                responseData = EntityUtils.toString(response.getEntity(),
                        "UTF-8");
            } else{
                responseData = "{'error_code':'"+response.getStatusLine().getStatusCode()+"'}";
            }
        } catch (Exception e) {
            responseData = "{'error_code':'500'}";
            e.printStackTrace();
        }
        return responseData;
    }

    /**
     * 获取httpclient，解决访问https请求时报ssl异常
     * 
     * @return
     */
    private static HttpClient getNewHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore
                    .getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new MFSnsSSLSocketFactoryEx(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(
                    params, registry);

            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }

}
