package com.atmob.voiceai.utils;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import atmob.okhttp3.ResponseBody;
import atmob.reactivex.rxjava3.observers.DefaultObserver;

public abstract class FileDownLoadObserver<T> extends DefaultObserver<T> {

    public abstract void onDownLoadStart();

    //下载成功的回调
    public abstract void onDownLoadSuccess(T t);

    //下载失败回调
    public abstract void onDownLoadFail(Throwable throwable);


    @Override
    protected void onStart() {
        super.onStart();
        onDownLoadStart();
    }

    @Override
    public void onNext(T t) {
        onDownLoadSuccess(t);
    }

    @Override
    public void onError(Throwable e) {
        onDownLoadFail(e);
    }

    @Override
    public void onComplete() {

    }

    private void copyStream(InputStream is, OutputStream os) throws IOException {
        byte[] buf = new byte[2048];
        int n;
        while ((n = is.read(buf)) > 0) {
            os.write(buf, 0, n);
        }
        os.flush();
    }


    public File saveFile(ResponseBody responseBody, String destFileDir, String destFileName) {
        File file = null;
        File dir = new File(destFileDir);

        try {
            if (!dir.exists()) {
                dir.mkdirs();
            }

            file = new File(dir, destFileName);

            try (
                    InputStream is = new BufferedInputStream(responseBody.byteStream());
                    FileOutputStream fos = new FileOutputStream(file);
                    OutputStream os = new BufferedOutputStream(fos);
            ) {
                copyStream(is, os);
            }

        } catch (IOException e) {
            Log.d("FileDownLoadObserver", "saveFile: " + e.getMessage());
        }

        return file;
    }
}
