package com.haven.wallpapers.Utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;

import com.haven.wallpapers.MyApp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Save {
    public static Uri saveToGallery(Context context, InputStream photoFile) {
        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;
        ContentResolver contentResolver = context.getContentResolver();
        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 = contentResolver.insert(collectionUri, contentValues);
        if (imageUri == null) {
            return null;
        }

        OutputStream outputStream = null;
        try {
            int byteLength = 0;
            byte[] bytes = new byte[4096];
            outputStream = contentResolver.openOutputStream(imageUri);
            while ((byteLength = photoFile.read(bytes)) != -1) {
                outputStream.write(bytes, 0, byteLength);
            }
            photoFile.close();
            outputStream.close();

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

        } catch (Exception exception) {

            return null;
        }
    }


    public static  boolean writeFile(InputStream input, String filePath) {
        try {
            // Create a buffer for reading bytes from the input stream
            byte[] byteArray = new byte[4096];
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            int bytesRead;

            // Read from the input stream and write to the output stream
            while ((bytesRead = input.read(byteArray)) != -1) {
                output.write(byteArray, 0, bytesRead);
            }

            // Create a File object for the given file path
            File fileDe = new File(filePath);
            // Check if file doesn't exist, create a new file
            if (!fileDe.exists()) {
                fileDe.createNewFile();
            }

            // Write the content to the file
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            fileOutputStream.write(output.toByteArray());

            // Close streams
            output.close();
            fileOutputStream.close();

            return true;
        } catch (IOException ex) {
            // Log the error message
            Log.d("-----------", "---------ex=" + ex.getMessage());
            return false;
        }
    }



    public static String getSaveFilePath( String imId) {
        // Return the file path by concatenating cache directory and image ID with the .jpg extension
        return MyApp.getmAppContext().getCacheDir().getAbsolutePath() + "/" + imId + ".jpg";
    }


    public static String saveDrawableToFile(Drawable drawable, String saveFilePath) {
        // 将 Drawable 转换为 Bitmap
        Bitmap bitmap = getMyBitmap(drawable);


        // 创建要保存的文件
        File file = new File(saveFilePath);
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(file);

            // 将 Bitmap 写入文件 (使用 PNG 格式，可改为 JPEG)
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return file.getAbsolutePath();
    }


    private static Bitmap getMyBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        // 创建一个空白的 Bitmap
        Bitmap bitmap = Bitmap.createBitmap(
                drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                Bitmap.Config.ARGB_8888);

        // 在 Canvas 上绘制 Drawable
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }
}
