package com.example.wallpapermagazine

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream

object DealData {





//    fun downloadFile(
//        url: String,
//        savePath: String,
//        result: (Boolean, input: InputStream?) -> Unit
//    ) {
//        var client = OkHttpClient()
//        var request = Request.Builder().url(url).build()
//        var call = client.newCall(request)
//        call.enqueue(object : Callback {
//            override fun onFailure(call: Call, e: IOException) {
//                result.invoke(false, null)
//            }
//
//            override fun onResponse(call: Call, response: Response) {
//                response.body?.run {
//                    val byteStream = byteStream()
//                    val writeFile = writeFile(byteStream, savePath)
//                    result.invoke(writeFile, byteStream)
//                } ?: run {
//                    result.invoke(false, null)
//                }
//            }
//        })
//    }

    fun writeFile(input: InputStream, filePath: String): Boolean {
        try {
            val byte = ByteArray(4096)
            val output = ByteArrayOutputStream()
            var l: Int
            while (input.read(byte).also { l = it } != -1) {
                output.write(byte, 0, l)
            }
            val fileDe = File(filePath)
            if (!fileDe.exists()) {
                fileDe.createNewFile()
            }
            val fileOutputStream = FileOutputStream(filePath)
            fileOutputStream.write(output.toByteArray())
            output.close()
            fileOutputStream.close()
            return true
        } catch (ex: Exception) {
            Log.d("-----------", "---------ex=" + ex.message)
            return false
        }


    }

    private fun saveImageQ(imagePath: String, context: Context): Boolean {
        return try {
            val contentResolver = context.contentResolver
            val contentValues =
                getImageContentValues(File(imagePath))
            val localUri = contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                contentValues
            )
            // 拷贝到指定uri,如果没有这步操作，android11不会在相册显示
            val out = context.contentResolver.openOutputStream(localUri!!)
            copyFile(imagePath, out)

            contentValues.clear();
            contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
            contentValues.putNull(MediaStore.MediaColumns.DATE_EXPIRES);
            contentResolver.update(localUri, contentValues, null, null);
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    private fun getImageContentValues(paramFile: File): ContentValues {
        val time = System.currentTimeMillis()
        val localContentValues = ContentValues()
        localContentValues.put(MediaStore.Images.Media.TITLE, paramFile.name)
        localContentValues.put(MediaStore.Images.Media.DISPLAY_NAME, paramFile.name)
        localContentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
        localContentValues.put(MediaStore.Images.Media.RELATIVE_PATH, getSavePath())
//        localContentValues.put(MediaStore.Images.Media.DATE_MODIFIED, time / 1000)
//        localContentValues.put(MediaStore.Images.Media.DATE_ADDED, time / 1000)
        return localContentValues
    }

    private fun getSavePath(): String {

        return ""
    }

    private fun saveImage(imagePath: String, context: Context): Boolean {
        return try {
            val path = getSavePath() + File.separator + File(imagePath).name
            val newFile = File(path)
            if (!newFile!!.parentFile.exists()) {
                newFile!!.parentFile.mkdirs()
            }
            val out = newFile.outputStream()
            copyFile(imagePath, out)

            val uri = Uri.fromFile(newFile)
            context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
            out.close()
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    private fun copyFile(oldPath: String, out: OutputStream?): Boolean {
        try {
            var bytesum = 0
            var byteread = 0
            val oldFile = File(oldPath)
            if (oldFile.exists()) {
                // 读入原文件
                val inStream: InputStream = FileInputStream(oldPath)
                val buffer = ByteArray(1444)
                while (inStream.read(buffer).also { byteread = it } != -1) {
                    bytesum += byteread //字节数 文件大小
                    println(bytesum)
                    out!!.write(buffer, 0, byteread)
                }
                inStream.close()
                out!!.close()
                return true
            } else {
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return false
    }


    fun saveToGallery(context: Context, inputStream: InputStream): Uri? {
        val displayName = "${System.currentTimeMillis()}.jpg"

        Log.d(WallPaperSelect.TAG, "----------------displayName=${displayName}")
        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, displayName)
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                put(MediaStore.Images.Media.IS_PENDING, 1)
            }
        }

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

        val imageUri = contentResolver.insert(collectionUri, contentValues)

        imageUri?.let { uri ->
            try {
                contentResolver.openOutputStream(uri)?.use { outputStream ->
//                    val inputStream = FileInputStream(photoFile)
                    inputStream.copyTo(outputStream)
                    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(uri, contentValues, null, null)
                } else {

                }
                return uri
            } catch (e: IOException) {
                Log.d(WallPaperSelect.TAG, "-----------------e=${e.printStackTrace()}")
                return null
            }
        } ?: run {
            Log.d(WallPaperSelect.TAG, "----------------false")
            return null
        }
    }

    fun saveFreshAppImageToGallery(context: Context, bitmap: Bitmap) {
        val bitmap = bitmap
        val displayName = "${System.currentTimeMillis()}.jpg"

        val values = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, displayName)
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000)
        }

        val contentResolver = context.contentResolver
        val collection =
            MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        val item = contentResolver.insert(collection, values)

        item?.let { uri ->
            try {
                val outputStream = contentResolver.openOutputStream(uri)
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream!!)
                outputStream.close()

                Log.d(WallPaperSelect.TAG, "------------------Save successfully!")
                val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                mediaScanIntent.data = uri
                context.sendBroadcast(mediaScanIntent)
            } catch (e: Exception) {
                Log.d(WallPaperSelect.TAG, "------------------Save Failed!")
                e.printStackTrace()
            }
        }

    }
}