package com.app.wallpaper.donwload;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class a {
    public static Uri saveToGallery(Context context, InputStream inputStream) {
        String displayName = System.currentTimeMillis()+".jpg";
        ContentValues contentValues = new ContentValues();
        Log.d("-----------------", "saveToGallery: "+displayName);
        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;
        }
//        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            int byteLength = 0;
            byte[] bytes = new byte[4096];
            outputStream = contentResolver.openOutputStream(imageUri);
//            inputStream = new FileInputStream(photoFile);
            while ((byteLength = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, byteLength);
            }
            inputStream.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;
        }
    }
}
