package com.yeejoin.amos.speech.util;

import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * okHttp客户端
 */
public class HttpUtil {

    static OkHttpClient client = new OkHttpClient
            .Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .build();

    public static String sendPostFile(String url, HashMap<String, String> headers, File speechFile) {
        RequestBody body;
        if (!speechFile.isFile()) {
            System.err.println("The filePath is not a file: " + speechFile.getPath());
            return null;
        } else {
            body = RequestBody.create(MediaType.parse("application/octet-stream"), speechFile);
        }
        Headers.Builder hb = new Headers.Builder();
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                hb.add(entry.getKey(), entry.getValue());
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .headers(hb.build())
                .post(body)
                .build();
        return getResponseWithTimeout(request);
    }

    private static String getResponseWithTimeout(Request request) {
        String result = null;
        try {
            Response s = client.newCall(request).execute();
            assert s.body() != null;
            result = s.body().string();
            s.close();
        } catch (SocketTimeoutException e) {
            System.err.println("get result timeout");
        } catch (IOException e) {
            System.err.println("get result error " + e.getMessage());
        }
        return result;
    }
}