package com.gh.gamecenter.common.retrofit;

import android.os.Handler;
import android.os.Looper;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

public class FileRequestBody<T> extends RequestBody {

    private RetrofitCallback<T> callback;

    private File mFile;

    private int DEFAULT_BUFFER_SIZE = 1024 * 8;


    public FileRequestBody(File file, RetrofitCallback<T> callback) {
        super();
        this.mFile = file;
        this.callback = callback;
    }

    @Override
    public long contentLength() throws IOException {
        return mFile.length();
    }

    @Override
    public MediaType contentType() {
        return MediaType.parse("multipart/form-data;boundary=" + getBoundary());
    }

    // 注意 addNetworkInterceptor ->HttpLoggingInterceptor 会调用两遍
    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        long fileLength = mFile.length();
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        FileInputStream in = new FileInputStream(mFile);
        long uploaded = 0;

        try {
            int read;
            Handler handler = new Handler(Looper.getMainLooper());
            while ((read = in.read(buffer)) != -1) {
                uploaded += read;
                sink.write(buffer, 0, read);
                // update progress on UI thread
                handler.post(new ProgressUpdater(uploaded, fileLength));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            in.close();
        }
    }

    private String getBoundary() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }

    private class ProgressUpdater implements Runnable {
        private long mUploaded;
        private long mTotal;

        public ProgressUpdater(long uploaded, long total) {
            mUploaded = uploaded;
            mTotal = total;
        }

        @Override
        public void run() {
            callback.onProgress(mTotal, mUploaded);
        }
    }
}
