package com.key.vibekeyboard.utils;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.key.vibekeyboard.viewmodel.callbacks.DownloadCallback;

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

public class DownloadUtils {

    public static void downloadFile(Context context, String url, DownloadCallback callback) {
        Glide.with(context)
                .asFile()
                .load(url)
                .listener(new RequestListener<File>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<File> target, boolean isFirstResource) {
                        try {
                            callback.onDownloadCall(false, null);
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        }
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(@NonNull File resource, @NonNull Object model, Target<File> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                        try {
                            File externalDir = context.getExternalFilesDir(null);
                            if (externalDir == null) {
                                externalDir = context.getFilesDir();
                            }

                            File downloadDir = new File(externalDir, "DownloadedFiles");
                            if (!downloadDir.exists()) {
                                boolean mkdirs = downloadDir.mkdirs();
                            }

                            File destinationFile = new File(downloadDir, resource.getName());
                            FileUtils.cloneFile(resource, destinationFile);

                            callback.onDownloadCall(true, destinationFile);
                            Log.d("--------", "resource:  " + destinationFile);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        return false;
                    }
                }).preload();
    }

}
