package com.apps.chillscreen.tool;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;


public class DownloadUtils {
    private static final Logger LOGGER=Logger.getLogger(DownloadUtils.class.getName());
    public interface DownloadCallback{
        void onResult(boolean success, InputStream inputStream);
    }
    public static Call downloadFile(String url, String savePath, DownloadCallback callback){
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder().url(url).build();
        Call call=client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                LOGGER.severe("Download failed: " + e.getMessage());
                callback.onResult(false,null);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                try(ResponseBody responseBody=response.body()){
                    if(responseBody!=null){
                        InputStream inputStream=responseBody.byteStream();
                        boolean writeSuccess=writeFile(inputStream,savePath);
                        callback.onResult(writeSuccess,inputStream);
                    }else{
                        LOGGER.warning("Empty response body");
                        callback.onResult(false,null);
                    }
                }catch (Exception e){
                    LOGGER.severe("Error processing response: " + e.getMessage());
                    callback.onResult(false,null);
                }
            }
        });
        return call;
    }

    private static boolean writeFile(InputStream inputStream,String filePath){
        File file=new File(filePath);
        try {
            File parent=file.getParentFile();
            if(parent!=null&&!parent.exists()){
                parent.mkdirs();
            }
            try(FileOutputStream fos=new FileOutputStream(file)) {
                byte[] buffer=new byte[4096];
                int byteRead;
                while ((byteRead=inputStream.read(buffer))!=-1){
                    fos.write(buffer,0,byteRead);
                }
                return true;
            }
        }catch (Exception e){
            LOGGER.severe("File write error: " + e.getMessage());
            return false;
        }
    }
}
