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.
 */
public class MultipartBodyMaker {
    MultipartBody.Builder builder;

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

    public List<MultipartBody.Part> makeParts() {
        return builder.build().parts();
    }

    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 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;
        }

        public Builder addDataPart(String name, String value) {
            builder.addFormDataPart(name, value);
            return this;
        }

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

    }
}
