package com.cooleshow.base.utils;

import com.cooleshow.base.data.net.UploadRequestBody;
import com.cooleshow.base.rx.BaseObserver;

import java.io.File;
import java.util.List;

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

public class RequestBodyUtil {
    /**
     * 将文件路径数组封装为{@link List < MultipartBody.Part>}
     *
     * @param key 对应请求正文中name的值。目前服务器给出的接口中，所有图片文件使用<br>
     *            同一个name值，实际情况中有可能需要多个
     */

    public static MultipartBody.Part filesToMultipartBodyParts(File files, String key) {

        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), files);
        MultipartBody.Part part = MultipartBody.Part.createFormData(key, files.getName(), requestBody);

        return part;
    }

    public static MultipartBody.Part filesToMultipartBodyParts(File files, String key, String mediaType) {
        RequestBody requestBody = RequestBody.create(MediaType.parse(mediaType), files);
        MultipartBody.Part part = MultipartBody.Part.createFormData(key, files.getName(), requestBody);

        return part;
    }

    public static MultipartBody.Part filesToMultipartBodyParts(File files, String key, String mediaType, BaseObserver observer) {
        RequestBody request = RequestBody.create(MediaType.parse(mediaType), files);
        UploadRequestBody requestBody = new UploadRequestBody(request, observer);
        MultipartBody.Part part = MultipartBody.Part.createFormData(key, files.getName(), requestBody);
        return part;
    }

    /**
     * 将参数封装成requestBody形式上传参数
     *
     * @param param 参数
     * @return RequestBody
     */
    public static RequestBody convertToRequestBody(String param) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), param);
        return requestBody;
    }

    /**
     * 将参数封装成requestBody Json形式上传参数
     *
     * @param param 参数
     * @return RequestBody
     */
    public static RequestBody convertToRequestBodyJson(String param) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), param);
        return requestBody;
    }

    /**
     * 将文件进行转换
     *
     * @param param 为文件类型
     * @return
     */
    public static RequestBody convertToRequestBodyMap(File param) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), param);
        return requestBody;
    }
}
