package com.adealink.weparty.imageselect.clip

import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.ActivityResultRegistry
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner

abstract class ClipImageLifecycleObserver(
    private val registry: ActivityResultRegistry,
    private val registerKey: String = "ClipImage"
) : DefaultLifecycleObserver {
    private lateinit var launcher: ActivityResultLauncher<ClipImageRequest>

    override fun onCreate(owner: LifecycleOwner) {
        launcher = registry.register(registerKey, owner, ClipImageContract()) {
            onResult(it.resultCode, it.inputPath, it.outputPath)
        }
    }

    fun launch(
        inputPath: String,
        outputPath: String,
        clipParamData: ClipParamData?
    ) {
        launcher.launch(
            ClipImageRequest(
                inputPath,
                outputPath,
                clipParamData
            )
        )
    }

    abstract fun onResult(resultCode: Int, inputPath: String, outputPath: String)

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        launcher.unregister()
    }

}