package com.sobot.network.http.request;

import com.sobot.network.http.builder.PostMultipartFormBuilder;
import com.sobot.network.http.callback.Callback;

import java.io.UnsupportedEncodingException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

public class PostMultipartFormRequest extends OkHttpRequest {
    private List<PostMultipartFormBuilder.FileInput> files;

    public PostMultipartFormRequest(String url, Object tag, Map<String, Object> params,
                                    Map<String, String> headers, List<PostMultipartFormBuilder.FileInput> files) {
        super(url, tag, params, headers);
        this.files = files;
    }

    @Override
    protected RequestBody buildRequestBody() {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        addParams(builder);

        for (int i = 0; i < files.size(); i++) {
            PostMultipartFormBuilder.FileInput fileInput = files.get(i);
            RequestBody fileBody = RequestBody.create(
                    MediaType.parse(guessMimeType(fileInput.filename)),
                    fileInput.file);
            try {
                builder.addFormDataPart(fileInput.key, URLEncoder.encode(fileInput.filename, "UTF-8"),
                        fileBody);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return builder.build();
    }

    @SuppressWarnings("rawtypes")
    @Override
    protected RequestBody wrapRequestBody(RequestBody requestBody,
                                          final Callback callback) {
        ProgressRequestBody progressRequestBody = new ProgressRequestBody(requestBody, callback);
        progressRequestBody.setInterceptor(uploadInterceptor);
        return progressRequestBody;
    }

    @Override
    protected Request buildRequest(RequestBody requestBody) {
        return builder.post(requestBody).build();
    }

    private String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        path = path.replace("#", "");   //解决文件名中含有#号异常的问题
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    private void addParams(MultipartBody.Builder builder) {
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                builder.addPart(
                        Headers.of("Content-Disposition", "form-data; name=\""
                                + key + "\""),
                        RequestBody.create(null, params.get(key).toString()));
            }
        }
    }

    private void addParams(FormBody.Builder builder) {
        if (params != null) {
            for (String key : params.keySet()) {
                if (params.get(key) != null) {
                    builder.add(key, params.get(key).toString());
                }
            }
        }
    }

}
