package com.aiosman.ravenow.ui.composables

import android.app.Activity
import android.content.Context
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import com.aiosman.ravenow.utils.Utils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import java.io.File

/**
 * 选择图片并压缩
 */
@Composable
fun pickupAndCompressLauncher(
    context: Context,
    scope: CoroutineScope,
    maxSize: Int = 512,
    quality: Int = 85,
    onImagePicked: (Uri, File) -> Unit
) = rememberLauncherForActivityResult(
    contract = ActivityResultContracts.StartActivityForResult()
) { result ->
    if (result.resultCode == Activity.RESULT_OK) {
        val uri = result.data?.data
        uri?.let {
            scope.launch {
                // Compress the image
                val file = Utils.compressImage(context, it, maxSize = maxSize, quality = quality)
                // Check the compressed image size
                onImagePicked(it, file)
            }
        }
    }
}