package tech.starwin.utils;

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

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

/**
 * Created by SiKang on 2018/9/28.
 * 用于创建 Retrofit 上传时的 MultipartBody类型参数
 */
public class MultipartBodyMaker {
    MultipartBody.Builder builder;

    private MultipartBodyMaker(MultipartBody.Builder builder) {
        this.builder = builder;
    }

    /**
     * 创建多个 不同参数类型的 MultipartBody.Part
     * 参数内容使用 Builder 配置
     */
    public List<MultipartBody.Part> makeParts() {
        return builder.build().parts();
    }

    /**
     * 创建一个只包含一个文件的 MultipartBody.Part
     */
    public static MultipartBody.Part makeSimplePart(String name, File file) {
        MediaType mediaType = MediaType.parse(FileUtils.getMimeType(file));
        RequestBody requestFile = RequestBody.create(mediaType, file);
        return MultipartBody.Part.createFormData(name, file.getName(), requestFile);
    }

    public static MultipartBody.Part makeSimplePart(String name, String value) {
        return MultipartBody.Part.createFormData(name, value);
    }

    public static class Builder {
        MultipartBody.Builder builder;

        public Builder() {
            builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);
        }

        /**
         * 加入单个文件
         */
        public Builder addDataPart(String name, File file) {
            RequestBody imageBody = RequestBody.create(MediaType.parse(FileUtils.getMimeType(file)), file);
            builder.addFormDataPart(name, file.getName(), imageBody);
            return this;
        }

        /**
         * 加入多个文件
         */
        public Builder addDataPart(String name, List<File> files) {
            for (File file : files) {
                RequestBody imageBody = RequestBody.create(MediaType.parse(FileUtils.getMimeType(file)), file);
                builder.addFormDataPart(name, file.getName(), imageBody);
            }
            return this;
        }

        /**
         * 加入String类型参数
         */
        public Builder addDataPart(String name, String value) {
            builder.addFormDataPart(name, value);
            return this;
        }

        public MultipartBodyMaker build() {
            return new MultipartBodyMaker(builder);
        }

    }
}
