package com.bxzk.afxj.retrofit;

import com.bxzk.afxj.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;

public class DownloadUtils {
    private static final String TAG = "DownloadUtils";
    private static final int DEFAULT_TIMEOUT = 15;
    private Retrofit retrofit;
    private RxDownloadListener listener;
    private String baseUrl = "http://www.wanandroid.com/blogimgs/";
    private String downloadUrl;

    public DownloadUtils(RxDownloadListener listener,Retrofit retrofit) {
        this.listener = listener;
        this.retrofit = retrofit;
    }

    public File file;
    /**
     * 开始下载
     *
     * @param filePath
     */
    public File download(final String filePath, String fileUrl) {
//        retrofit = ApiManager.getInstence(listener).getRetrofit();
        // subscribeOn()改变调用它之前代码的线程
        // observeOn()改变调用它之后代码的线程
        if(listener != null) {
            listener.onStartDownload();
        }
        retrofit.create(DownloadService.class)
                .downloadFile(fileUrl)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .map(new Function<ResponseBody, InputStream>() {
                    @Override
                    public InputStream apply(ResponseBody responseBody) throws Exception {
                        return responseBody.byteStream();
                    }
                })
                .observeOn(Schedulers.computation()) // 用于计算任务
                .doOnNext(new Consumer<InputStream>() {
                    @Override
                    public void accept(InputStream inputStream) throws Exception {
                        file = writeFile(inputStream, filePath);

                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<InputStream>() {
                    @Override
                    public void accept(InputStream inputStream) throws Exception {
                        Log.e("ty","成功");
                        if(listener != null) {
                            listener.onFinishDownload(file);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.e("ty","错误");
                        if(listener != null) {
                            listener.onFail(throwable.getMessage());
                        }
                    }
                });
        return file;
    }

    /**
     * 将输入流写入文件
     *
     * @param inputString
     * @param filePath
     */
    private File writeFile(InputStream inputString, String filePath)  throws Exception{
        int index = filePath.lastIndexOf("/");
        String substring = filePath.substring(0, index);
        File file = new File(substring);
//        try {
            if (!file.exists()) {
                file.mkdirs();
            }
            File dir = new File(filePath);
            if (dir.exists()) {
                dir.delete();
            }
            FileOutputStream fos = null;
            fos = new FileOutputStream(dir);
            byte[] b = new byte[1024];

            int len;
            while ((len = inputString.read(b)) != -1) {
                fos.write(b, 0, len);
            }
            inputString.close();
            fos.close();
            return dir;
//        } catch (Exception e) {
//            listener.onFail(e.getMessage());
//        }


    }

}
