package com.atmob.voiceai.utils;


import androidx.annotation.NonNull;


import java.io.File;

import atmob.okhttp3.OkHttpClient;
import atmob.reactivex.rxjava3.core.Single;
import atmob.reactivex.rxjava3.core.SingleOnSubscribe;
import atmob.rxjava.utils.RxJavaUtil;

public class VoiceFileUtil {


    /**
     * 先判断本地是否有，没有再下载，然后返回
     *
     * @param url
     * @return
     */
    public static Single<File> getVoiceFile(OkHttpClient okHttpClient, @NonNull String url) {
        return Single.create((SingleOnSubscribe<File>) emitter -> {
                    File localFile = net2LocalFile(url);
                    DownloadUtils.downLoadCompareBeforeLocal(okHttpClient, url, localFile, DownloadUtils.voiceFile, DownloadUtils.FILE_PREFIX + getFileName(url), new FileDownLoadObserver<File>() {
                        @Override
                        public void onDownLoadStart() {

                        }

                        @Override
                        public void onDownLoadSuccess(File file) {
                            emitter.onSuccess(file);
                        }

                        @Override
                        public void onDownLoadFail(Throwable throwable) {
                            emitter.onError(throwable);
                        }

                    });
                })
                .compose(RxJavaUtil.SingleSchedule.io2Main());
    }

    private static File net2LocalFile(@NonNull String url) {
        String fileName = DownloadUtils.FILE_PREFIX + getFileName(url);
        return new File(DownloadUtils.voiceFile, fileName);
    }

    private static String getFileName(@NonNull String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }
}
