package com.atmob.voiceai.utils;

import java.io.File;
import java.io.IOException;

import atmob.okhttp3.OkHttpClient;
import atmob.okhttp3.Request;
import atmob.okhttp3.Response;
import atmob.okhttp3.ResponseBody;
import atmob.reactivex.rxjava3.core.Observable;
import atmob.reactivex.rxjava3.core.ObservableOnSubscribe;
import atmob.reactivex.rxjava3.schedulers.Schedulers;

public class DownloadUtils {

    public static final String FILE_PREFIX = "VoiceAI_";

    public static File voiceFile = FileUtils.getVoiceDownloadSaveRootFile();

    private DownloadUtils() {

    }


    public static void downLoad(OkHttpClient client, String url, final File rootFile, final String fileName,
                                final FileDownLoadObserver<File> fileDownLoadObserver) {
        Observable.create((ObservableOnSubscribe<ResponseBody>) emitter -> {
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    try (Response response = client.newCall(request).execute()) {
                        if (!response.isSuccessful()) {
                            emitter.onError(new IOException("Failed to download audio: " + response));
                            return;
                        }
                        ResponseBody body = response.body();
                        if (body == null) {
                            emitter.onError(new IOException("Response body is null"));
                            return;
                        }
//                        AtmobLog.d("zk", String.format("文件类型为%s，文件大小为%d", response.body().contentType().toString(), response.body().contentLength()));
                        emitter.onNext(body);
                        emitter.onComplete();
                    } catch (IOException e) {
                        emitter.onError(e);
                    }
                })
                .map(responseBody -> fileDownLoadObserver.saveFile(responseBody,
                        rootFile.getPath(), fileName))
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .map(file -> {
                    if (file == null) {
                        throw new IOException("Failed to save file");
                    }
                    return file;
                })
                .subscribe(fileDownLoadObserver);
    }


    public static void downLoadCompareBeforeLocal(OkHttpClient client, String url, final File localFile, final File rootFile, final String fileName,
                                                  final FileDownLoadObserver<File> fileDownLoadObserver) {
        Observable.create((ObservableOnSubscribe<Object>) emitter -> {
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    try (Response response = client.newCall(request).execute()) {
                        if (!response.isSuccessful()) {
                            emitter.onError(new IOException("Failed to download audio: " + response));
                            return;
                        }
                        ResponseBody body = response.body();
                        if (body == null) {
                            emitter.onError(new IOException("Response body is null"));
                            return;
                        }
//                        AtmobLog.d("zk", String.format("文件类型为%s，文件大小为%d", response.body().contentType().toString(), response.body().contentLength()));
                        if (localFile == null || !localFile.exists() || localFile.length() != body.contentLength()) {
                            emitter.onNext(body);
                        } else {
                            emitter.onNext(localFile);
                        }
                        emitter.onComplete();
                    } catch (IOException e) {
                        emitter.onError(e);
                    }
                })
                .map(data -> {
                    if (data instanceof File) {
                        return (File) data;
                    } else {
                        ResponseBody responseBody = (ResponseBody) data;
                        return fileDownLoadObserver.saveFile(responseBody,
                                rootFile.getPath(), fileName);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .map(file -> {
                    if (file == null) {
                        throw new IOException("file is null");
                    }
                    return file;
                })
                .subscribe(fileDownLoadObserver);
    }

}
