package com.adealink.weparty.imageselect.comp

import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.ViewComponent
import com.adealink.weparty.imageselect.SelectImageLifecycleObserver
import com.adealink.weparty.imageselect.clip.ClipParamData
import com.adealink.weparty.imageselect.model.LocalMedia
import com.adealink.weparty.imageselect.model.MediaType

class TakeFromAlbumComp(
    lifecycleOwner: LifecycleOwner,
    val clipParamData: ClipParamData?,
    val onPhotoSelect: (path: String?, uri: String?) -> Unit
) : ViewComponent(lifecycleOwner) {
    private val selectImageObserver: SelectImageLifecycleObserver by fastLazy {
        object : SelectImageLifecycleObserver(requireActivity().activityResultRegistry) {

            override fun onResult(
                source: String,
                resultCode: Int,
                path: String?,
                uri: String?,
                mediaType: MediaType,
                mediaInfos: List<LocalMedia>?,
                fromPosition: Int?
            ) {
                if (path.isNullOrEmpty() || uri.isNullOrEmpty()) {
                    return
                }
                onPhotoSelect.invoke(path, uri)
            }

        }
    }

    override fun onCreate() {
        super.onCreate()
        lifecycle.addObserver(selectImageObserver)
    }

    fun takeFromAlbum() {
        selectImageObserver.launch(
            clipParamData = clipParamData, gifOpt = false
        )
    }
}