package com.atmob.voiceai.utils;

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 Exception {
        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)
            throws IOException {
        InputStream is = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            is = responseBody.byteStream();
            File dir = new File(destFileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            file = new File(dir, destFileName);
            fos = new FileOutputStream(file);
            copyStream(is, fos);
            return file;
        } catch (Exception e) {
            if (file != null) {
                file.delete();
            }
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null) fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }
}
