package com.colorful.keyboard.theme.net;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class RequestBuilder {
    private Map<String, Object> map;

    private RequestBuilder() {
        map = new HashMap<>();
    }

    public static RequestBuilder create() {
        return new RequestBuilder();
    }

    public static MultipartBody.Builder createMutiPartBodyBuilder() {
        return new MultipartBody.Builder();
    }

    public RequestBuilder putRequestParams(String key, Object value) {
        if (null != map) {
            map.put(key, value);
        }
        return this;
    }

    public RequestBody build() {
        return getRequestJson(map);
    }

    private static RequestBody getRequestJson(Map<String, Object> requestJson) {
       // System.out.println("RequestBuilder_debug: request json -> " + GsonHolder.getInstance().toJson(requestJson));
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), GsonHolder.getInstance().toJson(requestJson));
    }

    public static MultipartBody getMultipartBody(Map<String, RequestBody> request) {
//        File file = new File(path);
//        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//        MultipartBody.Builder builder = new MultipartBody.Builder();
//        builder.setType(MultipartBody.FORM);
//        builder.addFormDataPart("file", file.getName(), requestBody);
//        MultipartBody body = builder.build();//调用即可```

        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        for (String s : request.keySet()) {
            RequestBody body = request.get(s);
            builder.addFormDataPart(s, null, body);
        }

        MultipartBody body = builder.build();//调用即可```
        return body;
    }

    public static MultipartBody.Builder getFileFormdata(String path) {
        File file = new File(path);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("file", file.getName(), requestBody);
        return builder;
    }

    public static MultipartBody.Part getFileBodyPart(String key,File file){

        MultipartBody.Part body = MultipartBody.Part
                .createFormData(key, file.getName(),
                        RequestBody.create(MediaType.parse("multipart/form-data"), file));
        return body;

    }

}