package com.base.superfilemanager.activity.photocompress.photo

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.media.MediaScannerConnection
import android.os.Handler
import android.os.Looper
import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.io.IOException


private const val s = "temp"

object CompressionImageUtils {

    interface BitmapCallback {
        fun onBitmapReady(bitmap: Bitmap?, size: Long, position: Int)
    }

    fun compressImage(filePath: String, mode: Int, position: Int, callback: BitmapCallback) {
        Thread {
            try {
                val quality = when (mode) {
                    0 -> 95
                    50 -> 90
                    else -> 85
                }
                // 读取照片信息
                val options = BitmapFactory.Options()
                options.inJustDecodeBounds = true
                BitmapFactory.decodeFile(filePath, options)

                // 计算缩放比例
                val maxWidth = 1080
                val maxHeight = 1920
                val width = options.outWidth
                val height = options.outHeight
                var scale = 1
                while (width / scale > maxWidth || height / scale > maxHeight) {
                    scale *= 2
                }

                // 读取照片数据
                options.inJustDecodeBounds = false
                options.inSampleSize = scale
                val bitmap = BitmapFactory.decodeFile(filePath, options)
                if (bitmap == null) {
                    callback.onBitmapReady(null, 0, position)
                }
                // 旋转照片
                val orientation: Int = getOrientation(filePath)
                val matrix = Matrix()
                if (orientation == 90) {
                    matrix.postRotate(90f)
                } else if (orientation == 180) {
                    matrix.postRotate(180f)
                } else if (orientation == 270) {
                    matrix.postRotate(270f)
                }
                val rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)

                // 压缩照片
                val cacheFile = File.createTempFile(System.currentTimeMillis().toString(), ".jpg")

                val outputStream = FileOutputStream(cacheFile)
                rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
                outputStream.flush()
                outputStream.close()
                val compressedBitmap = BitmapFactory.decodeFile(cacheFile.path)
                val cacheSize = cacheFile.length()
                if (cacheFile.exists()) {
                    cacheFile.delete()
                }
                Log.d("glc","压缩后大小："+cacheSize)
                callback.onBitmapReady(compressedBitmap, cacheSize, position)

            } catch (e: IOException) {
                callback.onBitmapReady(null, 0, position)
            }

        }.start()
    }

    private fun getOrientation(filePath: String): Int {
        return try {
            val exif = ExifInterface(filePath)
            val orientation: Int = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED
            )
            if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                90
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                180
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                270
            } else {
                0
            }
        } catch (e: IOException) {
            0
        }
    }

    interface OnSaveBitmapListener {
        fun onSaveSuccess()
        fun onSaveFailed()
    }

    fun saveBitmapToFile(filePath: String?, mode: Int, bitmap: Bitmap,context: Context, listener: OnSaveBitmapListener) {
        Thread {
            val file = File(filePath)
            if (file.exists()) {
                file.delete()
            }
            try {
                val outputStream = FileOutputStream(file)
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
                updateMedia(filePath?:"",context)
                outputStream.flush()
                outputStream.close()
                if (listener != null) {
                    Handler(Looper.getMainLooper()).post(Runnable { listener.onSaveSuccess() })
                }
            } catch (e: IOException) {
                e.printStackTrace()
                if (listener != null) {
                    Handler(Looper.getMainLooper()).post(Runnable { listener.onSaveFailed() })
                }
            }
        }.start()
    }

    private fun updateMedia(file:String,context:Context){
        MediaScannerConnection.scanFile(context, arrayOf(file), null, null)

    }
}
