package com.wallpaper.wallpaperbox.util;

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
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 WallpaperUtils {

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

    public WallpaperUtils(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).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).execute(imageUrl);
            }
        }
    }

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

        private final Activity activity;
        private Exception taskException = null;

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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            toggleProgressVisibility(true);
        }

        @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 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
                    ? MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
                    : MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

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

            if (imageUri != null) {
                HttpURLConnection connection = null;
                try (InputStream inputStream = new URL(imageUrl).openStream();
                     OutputStream outputStream = activity.getContentResolver().openOutputStream(imageUri)) {

                    connection = (HttpURLConnection) new URL(imageUrl).openConnection();
                    connection.setDoInput(true);
                    connection.connect();

                    if (outputStream != null) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }

                    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) {
                    taskException = e;
                    activity.getContentResolver().delete(imageUri, null, null);
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(Uri uri) {
            super.onPostExecute(uri);
            toggleProgressVisibility(false);

            if (uri != null) {
                Toast.makeText(activity, "Image saved successfully", Toast.LENGTH_SHORT).show();
            } else {
                String errorMessage = taskException != null ? taskException.getMessage() : "Unknown error";
                Toast.makeText(activity, "Failed to save image: " + errorMessage, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void toggleProgressVisibility(boolean visible) {
        if (progressBar != null) {
            progressBar.setVisibility(visible ? View.VISIBLE : View.GONE);
        }
        if (overlayView != null) {
            overlayView.setVisibility(visible ? View.VISIBLE : View.GONE);
        }
    }
}

