package com.pcloud.book.group.tools;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

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

public final class Kit {

    private Kit() {

    }

    private static OkHttpClient httpClient = new OkHttpClient().newBuilder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS).build();

    private static final MediaType CONTENT_TYPE_FORM = MediaType
            .parse("application/json");


    public static String post(String url, String data) {
        RequestBody body = RequestBody.create(
                CONTENT_TYPE_FORM, data);
        Request request = new Request.Builder().url(url)
                .post(body).build();
        return exec(request);
    }


    public static String post(String url, Map<String,String> form) {

        FormBody.Builder builder = new FormBody.Builder();

        for(Map.Entry<String,String> entry: form.entrySet()){
            builder.add(entry.getKey(),entry.getValue());
        }

        FormBody formBody = builder.build();

        Request request = new Request.Builder().url(url)
                .post(formBody).build();
        return exec(request);
    }


    private static String exec(Request request) {
        try {
            Response response = httpClient.newCall(request)
                    .execute();
            if (!response.isSuccessful()) {
                throw new RuntimeException("Unexpected code " + response);
            }
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }






}
