package com.atmob.voiceai.utils;

import android.os.CancellationSignal;
import android.util.Log;

import androidx.annotation.NonNull;

import com.atmob.common.logging.AtmobLog;

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;

public abstract class FileDownLoadObserver<T> {

    private static final String TAG = FileDownLoadObserver.class.getSimpleName();

    public abstract void onDownLoadStart();

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

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


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


    public File saveFile(@NonNull CancellationSignal cancellationSignal, ResponseBody responseBody, String destFileDir, String destFileName) {
        AtmobLog.d(TAG, "start save file : fileDir = " + destFileDir + " , fileName = " + 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, cancellationSignal);
            }

        } catch (IOException e) {
            Log.d(TAG, "saveFile error: " + e.getMessage());
        }
        AtmobLog.d(TAG, "start save file over,file:" + file.getPath());
        return file;
    }
}
