package com.sketch.ar.artdrawing.importImage

import android.content.Context
import android.graphics.BitmapFactory
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.sketch.ar.artdrawing.dataBean.DataImport
import com.sketch.ar.artdrawing.databinding.AdapterImportImageBinding
import com.sketch.ar.artdrawing.utils.BaseAdapter
import com.sketch.ar.artdrawing.utils.ObjectBoxHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ImportImageAdapter(context: Context, var clickAction:(isDelete:Boolean, path:String)->Unit):
    BaseAdapter<DataImport, AdapterImportImageBinding>(context) {
    override fun getViewBinding(parent: ViewGroup?): AdapterImportImageBinding {

       return  AdapterImportImageBinding.inflate(
           LayoutInflater.from(parent?.context),
           parent,
           false
       )
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val itemHolder  = holder as VHolder<AdapterImportImageBinding>
        data[position].let {
            val beanUpload: DataImport = data[position]
            val path: String = beanUpload.uri.toString()
            CoroutineScope(Dispatchers.IO).launch {
                val bitmap = BitmapFactory.decodeFile(path)
                withContext(Dispatchers.Main) {
                    holder.vb.imPreview.setImageBitmap(bitmap)
                }
            }
            itemHolder.vb.cardView.setOnClickListener(View.OnClickListener {
                clickAction.invoke(false,path)

            })
            itemHolder.vb.delete.setOnClickListener(View.OnClickListener {
                val adapterPosition = holder.getAdapterPosition()
                ObjectBoxHelper.deleteImport(path)
                data.removeAt(adapterPosition)
                notifyItemRemoved(adapterPosition)
                clickAction.invoke(true,path)
            })
        }


    }


}