/**
 * BitmapUtils.kt
 * SkyLink Android 端 - 图像处理工具
 *
 * 提供 JPEG 到 Bitmap 的转换和其他图像处理功能
 *
 * @author flowzl
 * @date 2026-01-19
 */

package com.skylink.app.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import java.io.ByteArrayInputStream

object BitmapUtils {
    private const val TAG = "BitmapUtils"

    /**
     * 从 JPEG 字节数据解码为 Bitmap
     *
     * @param jpegData JPEG 数据字节数组
     * @param maxWidth 最大宽度 (用于缩放)
     * @param maxHeight 最大高度 (用于缩放)
     * @return 解码后的 Bitmap，失败返回 null
     */
    fun decodeBitmap(
        jpegData: ByteArray,
        maxWidth: Int = 1920,
        maxHeight: Int = 1080
    ): Bitmap? {
        return try {
            // 先解码获取尺寸
            val options = BitmapFactory.Options()
            options.inJustDecodeBounds = true
            BitmapFactory.decodeByteArray(jpegData, 0, jpegData.size, options)

            // 计算缩放比例
            val scale = calculateInSampleSize(options, maxWidth, maxHeight)
            options.inJustDecodeBounds = false
            options.inSampleSize = scale

            // 实际解码
            val bitmap = BitmapFactory.decodeByteArray(jpegData, 0, jpegData.size, options)
            // Log.i(TAG, "✓ Bitmap 解码成功: ${bitmap?.width}x${bitmap?.height}") // 移除高频日志
            bitmap
        } catch (e: Exception) {
            Log.e(TAG, "Bitmap 解码失败", e)
            null
        }
    }

    /**
     * 从输入流解码 Bitmap
     */
    fun decodeBitmapFromStream(
        jpegData: ByteArray,
        maxWidth: Int = 1920,
        maxHeight: Int = 1080
    ): Bitmap? {
        return try {
            val stream = ByteArrayInputStream(jpegData)
            val options = BitmapFactory.Options()
            options.inJustDecodeBounds = true
            BitmapFactory.decodeStream(stream, null, options)

            val scale = calculateInSampleSize(options, maxWidth, maxHeight)
            stream.reset()
            options.inJustDecodeBounds = false
            options.inSampleSize = scale

            BitmapFactory.decodeStream(stream, null, options)
        } catch (e: Exception) {
            Log.e(TAG, "从流解码 Bitmap 失败", e)
            null
        }
    }

    /**
     * 计算缩放比例
     */
    private fun calculateInSampleSize(
        options: BitmapFactory.Options,
        reqWidth: Int,
        reqHeight: Int
    ): Int {
        val (height: Int, width: Int) = options.run { outHeight to outWidth }
        var inSampleSize = 1

        if (height > reqHeight || width > reqWidth) {
            val halfHeight: Int = height / 2
            val halfWidth: Int = width / 2

            while (halfHeight / inSampleSize >= reqHeight &&
                   halfWidth / inSampleSize >= reqWidth
            ) {
                inSampleSize *= 2
            }
        }
        return inSampleSize
    }

    /**
     * 将 Bitmap 缩放到指定大小
     */
    fun scaleBitmap(bitmap: Bitmap, width: Int, height: Int): Bitmap {
        return Bitmap.createScaledBitmap(bitmap, width, height, true)
    }

    /**
     * 旋转 Bitmap
     */
    fun rotateBitmap(bitmap: Bitmap, degrees: Float): Bitmap {
        val matrix = android.graphics.Matrix()
        matrix.postRotate(degrees)
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    }

    /**
     * 获取 Bitmap 的大小（字节）
     */
    fun getBitmapSize(bitmap: Bitmap): Long {
        return (bitmap.byteCount).toLong()
    }
}
