package com.haven.wallpapers.Utils;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;


import com.haven.wallpapers.listener.OnDownloadListener;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadTask extends AsyncTask<String, Void, Boolean> {


    private OnDownloadListener listener;
    private Context context;

    public DownloadTask(OnDownloadListener listener, Context context) {
        this.listener = listener;
        this.context = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        String imageUrl = params[0];
        String type = params[1];
        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 = Save.saveToGallery(context, inputStream);
                if (uri == null) {
                    listener.onDownloadResult(false,inputStream,type);
                    return false;
                }
                listener.onDownloadResult(true,inputStream,type);
                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) {
                Log.e("--------------", "disconnect");
                connection.disconnect();
            }
        }
        return false;

    }

    @Override
    protected void onPostExecute(Boolean result) {
//        if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
//            activity.findViewById(R.id.progressbar).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();
//            }
//        }
    }
}
