package com.example.wallpapermagazine.donwload;

import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import com.example.wallpapermagazine.DealData;
import com.example.wallpapermagazine.WallPaperSelect;
import com.example.wallpapermagazine.action.DownloadListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageDownloadTask extends AsyncTask<String, Void, Boolean> {
    private Context context;
    private DownloadListener downloadListener;

    public ImageDownloadTask(Context context, DownloadListener listener) {
        this.context = context;
        downloadListener = listener;
    }


    @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 uri1 = DealData.INSTANCE.saveToGallery(WallPaperSelect.context, inputStream);


                if(uri1 == null){
                    return false;
                }else {
                    return true;
                }

//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                    ContentValues values = new ContentValues();
//                    values.put(MediaStore.Images.Media.DISPLAY_NAME, "downloaded_image_" + System.currentTimeMillis() + ".jpg");
//                    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
//                    values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
//                    Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//                    if (uri != null) {
//                        try (OutputStream outputStream = context.getContentResolver().openOutputStream(uri)) {
//                            byte[] buffer = new byte[1024];
//                            int bytesRead;
//                            while ((bytesRead = inputStream.read(buffer)) != -1) {
//                                outputStream.write(buffer, 0, bytesRead);
//                            }
//                            Log.e("ImageDownloadTask", "  true  uri =" + uri.getPath());
//                            return true;
//                        }
//                    }
//                } else {
//                    File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "download");
//                    if (!directory.exists()) {
//                        directory.mkdirs();
//                    }
//                    File outputFile = new File(directory, "downloaded_image_" + System.currentTimeMillis() + ".jpg");
//                    try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
//                        byte[] buffer = new byte[1024];
//                        int bytesRead;
//                        while ((bytesRead = inputStream.read(buffer)) != -1) {
//                            fileOutputStream.write(buffer, 0, bytesRead);
//                        }
//                        Log.e("ImageDownloadTask", "  true  outputFile =" + outputFile.getAbsolutePath());
//                        return true;
//                    }
//                }
            } else {
                Log.e("ImageDownloadTask", "Server returned HTTP " + responseCode + " " + connection.getResponseMessage());
                return false;
            }
        } catch (Exception e) {
            Log.e("ImageDownloadTask", "Error downloading image", e);
            return false;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

    }

    @Override
    protected void onPostExecute(Boolean result) {
        Log.e("ImageDownloadTask", "============" + result);
        if (downloadListener != null) {
            downloadListener.downloadResult(result);
        }

    }

}