package com.app.wallpaper.donwload;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.app.wallpaper.R;
import com.app.wallpaper.getdata.SetData;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageDownloadTask extends AsyncTask<String, Void, Boolean> {
    @SuppressLint("StaticFieldLeak")
    private Context context;
    private Activity activity;
    public ImageDownloadTask(Context context, Activity activity) {
        this.context = context;
        this.activity = activity;
    }
    @Override
    protected Boolean doInBackground(String... params) {
        String imageUrl = params[0];
        HttpURLConnection connection = null;
        try {
            URL url = new URL(imageUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                Uri uri = a.saveToGallery(SetData.getContext(), inputStream);
                if(uri == null){
                    return  false;
                }
                return  true;
            } else {
                Log.e("ImageDownloadTask", "Server returned HTTP " + responseCode + " " + connection.getResponseMessage());
            }
        } catch (Exception e) {
            Log.e("ImageDownloadTask", "Error downloading image", e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return false;

    }
    @Override
    protected void onPostExecute(Boolean result) {
        if(activity != null&& !activity.isFinishing() && !activity.isDestroyed()){
            activity.findViewById(R.id.progressbar1).setVisibility(View.GONE);
        if (result) {

            Toast.makeText(context, "Image downloaded successfully", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "Failed to download image", Toast.LENGTH_SHORT).show();
        }}
    }
}
