package com.dahe.mylibrary.net;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * 文件上传Interceptor
 */

public class FileInterceptor implements Interceptor {
    private static final String TAG = "FileInterceptor";
    private File mFile;

    public FileInterceptor(File mFile) {
        this.mFile = mFile;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        request = request.newBuilder()
                .post(RequestBody.create(MediaType.parse("application/file; charset=utf-8"), mFile))
                .build();
        Response response = chain.proceed(request);
        Log.i(TAG, "url= " + request.body());
        Log.i(TAG, "method= " + request.method());
        ResponseBody responseBody = response.body();
        //为了不消耗buffer，我们这里使用source先获得buffer对象，然后clone()后使用
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        //获得返回的数据
        Buffer buffer = source.buffer();
        //使用前clone()下，避免直接消耗
        String responseBodyStr = buffer.clone().readString(Charset.forName("UTF-8"));
        Log.i(TAG, "result-body= " + responseBodyStr);
        try {
            JSONObject jsonObject = new JSONObject(responseBodyStr);
            responseBody = ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.getString("response"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        response = response.newBuilder().body(responseBody).build();
        return response;
    }
}
