package com.adealink.weparty.imageselect.processor

import android.graphics.Bitmap
import com.adealink.frame.storage.file.imageProgressPath
import com.adealink.frame.util.ImageUtil
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.File
import java.util.UUID
import kotlin.coroutines.resume

/**
 * 图片缩小
 */
class ImageScaleDownProcessor(
    private val reqWidth: Int,
    private val reqHeight: Int,
    private val maxInSampleSize: Int = 1024 //2^10(缩小10倍)
): ImageProcessor() {
    override suspend fun process(path: String): String {
        return suspendCancellableCoroutine {
            val pictureSize = ImageUtil.getPictureSize(path)
            var newFilePath = File(
                imageProgressPath,
                "${UUID.randomUUID()}.jpg").absolutePath
            if (pictureSize.first > reqWidth || pictureSize.second > reqHeight) {
                //图片需要缩小
                val resizedBitmap: Bitmap? =
                    ImageUtil.scaleWithin(path, reqWidth, reqHeight, maxInSampleSize)
                if (resizedBitmap != null) {
                    ImageUtil.writeBitmapToFile(resizedBitmap, newFilePath)
                } else {
                    newFilePath = path
                }
            } else {
                newFilePath = path
            }
            if (it.isActive) {
                it.resume(newFilePath)
            }
        }
    }
}