package com.ruiwenliu.wrapper.http;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.ruiwenliu.wrapper.inter.UploadCallbacks;

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

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

public class ProgressRequestBody extends RequestBody {

    private File            mFile;
    private String          mPath;
    private String          mMediaType;
    private UploadCallbacks mListener;

    private int s = -1;

    private int mEachBufferSize = 1024;

    public ProgressRequestBody(final File file, String mediaType,  UploadCallbacks listener) {
        mFile = file;
        mMediaType = mediaType;
        mListener = listener;
    }

    @Override
    public MediaType contentType() {
        return MediaType.parse(mMediaType);
    }

    @Override
    public void writeTo(BufferedSink sink)
            throws IOException {
        if (sink instanceof Buffer) {
            return;
        }

        long            fileLength = mFile.length();
        byte[]          buffer     = new byte[mEachBufferSize];
        FileInputStream in         = new FileInputStream(mFile);
        long            uploaded   = 0;

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

            }
        } finally {
            in.close();
        }
    }

    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() {
            int i = (int) (100 * mUploaded / mTotal);
            if (s != i) {
                Log.i("progressrequestbody", "run:++ " + i);
                mListener.onProgressUpdate(i+ 1);
                s = i;
            }
        }
    }

    public interface UploadCallbacks {
        void onProgressUpdate(int percentage);
    }
}