package com.alipay.face.verify.fintechfacedemo.network;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * 网络请求
 */
public class SimpleNetworkRequestUtil {

    public final static String BASEURL = "http://faceverify.cloud.alipay.com/";

    public enum REQUEST_METHOD {
        POST,
        GET,
    }

    public static NetResponse doRequest(byte[] requestContent, String url) throws Exception {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Connection", "Keep-Alive");
        headers.put("Charset", "UTF-8");
        headers.put("Content-type", "application/json");
        return doRequest(url, headers, requestContent);
    }

    public static NetResponse doRequest(String requestUrl, Map<String, String> headers, byte[] requestBody) throws Exception {
        NetResponse netResponse = new NetResponse();
        HttpURLConnection conn = null;

        Log.d("MultiActionDemo", "requestUrl=" + requestUrl);

        URL requestObj = new URL(requestUrl);
        conn = (HttpURLConnection) requestObj.openConnection();
        conn.setReadTimeout(30000);
        conn.setConnectTimeout(30000);

        if (null != headers) {
            conn.setDoOutput(true);
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.setRequestProperty(header.getKey(), header.getValue());
            }
            conn.setRequestMethod(REQUEST_METHOD.POST.name());
        }else{
            conn.setRequestMethod(REQUEST_METHOD.GET.name());
        }
        if (null != requestBody) {
            OutputStream os = conn.getOutputStream();
            os.write(requestBody);
            os.flush();
            os.close();
        }

        conn.connect();

        int responseCode = conn.getResponseCode();
        byte[] responseBody;
        InputStream inputStream;
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 10];
        int length;
        boolean firstByteCome = false;
        while ((length = inputStream.read(buffer)) > 0) {
            if (!firstByteCome) {
                firstByteCome = true;
            }
            outputStream.write(buffer, 0, length);
        }
        responseBody = outputStream.toByteArray();
        netResponse.responseBody = responseBody;
        netResponse.rpcCode = responseCode;
        return netResponse;
    }
}
