package com.wallpaper.perfectwallpaper.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

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

public class GallerySaver {

    public static final int REQUEST_CODE_WRITE_EXTERNAL_STORAGE = 123;
    private final ProgressBar progressBar;
    private final ImageView overlayView;

    public GallerySaver(Context context, ProgressBar progressBar, ImageView overlayView) {
        this.progressBar = progressBar;
        this.overlayView = overlayView;
    }

    public void saveToGallery(Activity activity, String imageUrl) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            new SaveImageTask(activity, progressBar).execute(imageUrl);
        } else {
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
            } else {
                new SaveImageTask(activity, progressBar).execute(imageUrl);
            }
        }
    }

    private class SaveImageTask extends AsyncTask<String, Void, Uri> {

        private final Activity activity;
        private final ProgressBar progressBar;

        public SaveImageTask(Activity activity, ProgressBar progressBar) {
            this.activity = activity;
            this.progressBar = progressBar;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (progressBar != null) {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        protected Uri doInBackground(String... params) {
            String imageUrl = params[0];
            String displayName = System.currentTimeMillis() + ".jpg";
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, displayName);
            contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                contentValues.put(MediaStore.Images.Media.IS_PENDING, 1);
            }

            Uri collectionUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                collectionUri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
            } else {
                collectionUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            }

            Uri imageUri = activity.getContentResolver().insert(collectionUri, contentValues);

            if (imageUri != null) {
                try {
                    HttpURLConnection connection = (HttpURLConnection) new URL(imageUrl).openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream inputStream = connection.getInputStream();

                    try (OutputStream outputStream = activity.getContentResolver().openOutputStream(imageUri)) {
                        if (outputStream != null) {
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }
                        }
                    } finally {
                        inputStream.close();
                    }

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        contentValues.clear();
                        contentValues.put(MediaStore.Images.Media.IS_PENDING, 0);
                        activity.getContentResolver().update(imageUri, contentValues, null, null);
                    }

                    return imageUri;
                } catch (IOException e) {
                    Log.e("GallerySaver", "Error saving image to gallery", e);
                    activity.getContentResolver().delete(imageUri, null, null);
                    return null;
                }
            } else {
                Log.e("GallerySaver", "Failed to insert image into MediaStore");
                return null;
            }
        }

        @Override
        protected void onPostExecute(Uri uri) {
            super.onPostExecute(uri);
            if (progressBar != null && overlayView != null) {
                progressBar.setVisibility(View.GONE);
                overlayView.setVisibility(View.GONE);
            }

            if (uri != null) {
                Toast.makeText(activity, "Image downloaded", Toast.LENGTH_SHORT).show();
                Log.d("GallerySaver", "Image saved to gallery: " + uri);
            } else {
                Toast.makeText(activity, "StaticValue.key_download_failure", Toast.LENGTH_SHORT).show();
                Log.e("GallerySaver", "Download failure");
            }
        }
    }
}
