package com.ycgis.macall.personalcenter.p.request;



import com.ycgis.macall.personalcenter.p.callback.UploadProgressListener;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

/**
 * Created by macall on 2018-06-06.
 * copyright：ycgis
 */
public class UploadProgressResponsBody {

    public static RequestBody createCustomRequestBody(final MediaType contentType, final File file, final UploadProgressListener listener) {
        return new RequestBody() {
            @Override public MediaType contentType() {
                return contentType;
            }

            @Override public long contentLength() {
                return file.length();
            }

            @Override public void writeTo(@NotNull BufferedSink sink) throws IOException {
                Source source;
                try {
                    source = Okio.source(file);
                    Buffer buf = new Buffer();
                    long remaining = contentLength();
                    for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) {
                        sink.write(buf, readCount);
                        listener.onUploadProgress(contentLength(), remaining -= readCount, remaining == 0);
                    }
                    listener.onUploadDone(remaining);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
