package com.adealink.weparty.module.widget.form.field.picture.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.ext.findViewTreeLifecycleOwnerWhenAttach
import com.adealink.weparty.commonui.recycleview.adapter.BindingViewHolder
import com.adealink.weparty.commonui.recycleview.adapter.multitype.ItemViewBinder
import com.adealink.weparty.databinding.WidgetPicturePictureItemBinding
import com.adealink.weparty.module.widget.form.field.picture.PictureItemData


class PictureItemViewBinder(
    val onItemClick: (item: PictureItemData) -> Unit,
    val onDeleteClick: (item: PictureItemData) -> Unit
) :
    ItemViewBinder<PictureItemData, BindingViewHolder<WidgetPicturePictureItemBinding>>() {

    override fun onBindViewHolder(
        holder: BindingViewHolder<WidgetPicturePictureItemBinding>,
        item: PictureItemData,
    ) {
        holder.binding.root.onClick {
            onItemClick.invoke(item)
        }
        holder.binding.ivDelete.onClick {
            onDeleteClick.invoke(item)
        }
        if (item.data.isLocal()) {
            holder.binding.ivPicture.setImageURI(item.data.uri)
        } else if (item.data.isRemote()) {
            holder.binding.ivPicture.setImageUrl(item.data.url)
        } else {
            holder.binding.ivPicture.setImageUrl(null)
        }
        holder.binding.root.findViewTreeLifecycleOwnerWhenAttach { owner ->
            owner ?: return@findViewTreeLifecycleOwnerWhenAttach
            holder.binding.vUploadProgress.observeProgress(owner, item.data.mediaUpload)
        }
    }

    override fun onCreateViewHolder(
        inflater: LayoutInflater,
        parent: ViewGroup,
    ): BindingViewHolder<WidgetPicturePictureItemBinding> {
        return BindingViewHolder(
            WidgetPicturePictureItemBinding.inflate(
                inflater,
                parent,
                false
            )
        )
    }
}