package com.e6yun.project.sdk.api.utils;

import com.google.gson.Gson;
import okhttp3.*;
import okio.BufferedSink;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author Xue Xiang <xuexiang@e6yun.com>
 */
public class OkhttpClientUtils {

    /**
     * 连接超时时长，单位: 秒
     */
    private static final long TIMEOUT_CONNECT_SECONDS = 10;

    /**
     * 读数据超时时长，单位: 秒
     */
    private static final long TIMEOUT_READ_SECONDS = 30;

    /**
     * 写数据超时时长，单位: 秒
     */
    private static final long TIMEOUT_WRITE_SECONDS = 10;

    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    /**
     * 全局OkHttpClient
     */
    private static final OkHttpClient OK_HTTP_CLIENT =
            new OkHttpClient().newBuilder()
                    .connectTimeout(Duration.ofSeconds(TIMEOUT_CONNECT_SECONDS))
                    .readTimeout(Duration.ofSeconds(TIMEOUT_READ_SECONDS))
                    .writeTimeout(Duration.ofSeconds(TIMEOUT_WRITE_SECONDS)).build();


    public static HttpUrl buildUrlQueryString(String url, Map<String, String> parameters){
        HttpUrl.Builder huBuilder = HttpUrl.parse(url).newBuilder();
        if(MapUtils.isNotEmpty(parameters)){
            for(Map.Entry<String, String> entry : parameters.entrySet()){
                String name = entry.getKey();
                String value = entry.getValue();
                if(Objects.isNull(name)){
                    throw new IllegalArgumentException("参数的键不能空");
                }
                huBuilder.addQueryParameter(name, value);
            }
        }
        return huBuilder.build();
    }

    public static String get(String url, Map<String, String> parameters) throws IOException {
        HttpUrl httpUrl = buildUrlQueryString(url, parameters);
        final Request request = new Request.Builder().get().url(httpUrl).build();
        try (Response response = OK_HTTP_CLIENT.newCall(request).execute()) {
            return new String(response.body().bytes(), StandardCharsets.UTF_8);
        }
    }

    public static String postFormBody(String url, Map<String, String> parameters) throws IOException {
        HttpUrl.Builder huBuilder = HttpUrl.parse(url).newBuilder();
        FormBody.Builder fbBuilder = new FormBody.Builder();
        if(MapUtils.isNotEmpty(parameters)){
            for(Map.Entry<String, String> entry : parameters.entrySet()){
                String name = entry.getKey();
                String value = entry.getValue();
                if(Objects.isNull(name)){
                    throw new IllegalArgumentException("参数的键不能空");
                }
                fbBuilder.add(name, value);
            }
        }
        final Request request = new Request.Builder().post(fbBuilder.build()).url(huBuilder.build()).build();
        try (Response response = OK_HTTP_CLIENT.newCall(request).execute()) {
            return new String(response.body().bytes(), StandardCharsets.UTF_8);
        }
    }

    public static String postJsonBody(String url, Object parameters) throws IOException {
        HttpUrl.Builder huBuilder = HttpUrl.parse(url).newBuilder();
        Gson gson = new Gson();
        String json = gson.toJson(parameters);
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url(huBuilder.build())
                .post(body)
                .build();
        try (Response response = OK_HTTP_CLIENT.newCall(request).execute()) {
            return new String(response.body().bytes(), StandardCharsets.UTF_8);
        }
    }
}
