package com.tt.honeyDue.util

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.tt.honeyDue.platform.ImageData
import java.io.ByteArrayOutputStream

/**
 * Android implementation of image compression
 * Compresses images to JPEG format and ensures they don't exceed MAX_IMAGE_SIZE_BYTES
 */
actual object ImageCompressor {
    /**
     * Compress an ImageData to JPEG format with size limit
     * @param imageData The image to compress
     * @return Compressed image data as ByteArray
     */
    actual fun compressImage(imageData: ImageData): ByteArray {
        // Decode the original image
        val originalBitmap = BitmapFactory.decodeByteArray(
            imageData.bytes,
            0,
            imageData.bytes.size
        )

        // Compress with iterative quality reduction
        return compressBitmapToTarget(originalBitmap, ImageConfig.MAX_IMAGE_SIZE_BYTES)
    }

    /**
     * Compress a bitmap to target size
     */
    private fun compressBitmapToTarget(bitmap: Bitmap, targetSizeBytes: Int): ByteArray {
        var quality = ImageConfig.INITIAL_JPEG_QUALITY
        var compressedData: ByteArray

        do {
            val outputStream = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
            compressedData = outputStream.toByteArray()

            // If size is acceptable or quality is too low, stop
            if (compressedData.size <= targetSizeBytes || quality <= ImageConfig.MIN_JPEG_QUALITY) {
                break
            }

            // Reduce quality for next iteration
            quality -= 5
        } while (true)

        return compressedData
    }
}
