package com.convenient.android.common.activitycontracts

import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContract
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

/**
 * @classname BaseActivityResultLauncher
 * @author LiuXiaoLong
 * @date 2022-07-27 AM
 * @description 基础ActivityResult API, I:输入的参数， O：响应的数据
 */
open class BaseActivityResultLauncher<I, O>(
    caller: ActivityResultCaller,
    contract: ActivityResultContract<I, O>
) {

    private val launcher: ActivityResultLauncher<I>
    private var callback: ActivityResultCallback<O>? = null

    init {
        launcher = caller.registerForActivityResult(contract) { result: O ->
            callback?.onActivityResult(result)
            callback = null
        }
    }

    fun launch(input: I, callback: ActivityResultCallback<O>) {
        this.callback = callback
        launcher.launch(input)
    }

    fun launch(input: I) {
        launcher.launch(input)
    }
}


suspend fun <I, O> BaseActivityResultLauncher<I, O>.launchForResult(input : I) =
    suspendCancellableCoroutine<O> { cancellableContinuation ->
        launch(input){
            if (it != null){
                cancellableContinuation.resume(it)
            }else{
                cancellableContinuation.cancel()
            }
        }
    }