package com.drawing.drawsketch.upload

import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.drawing.drawsketch.BaseAdapter
import com.drawing.drawsketch.DbBase
import com.drawing.drawsketch.databinding.UploadAdapterBinding
import com.drawing.drawsketch.dbmodel.UpLoad
import com.drawing.drawsketch.preview.PreviewActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

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

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

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val itemHolder  = holder as VHolder<UploadAdapterBinding>
        data[position].let {
            val beanUpload: UpLoad = 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()
                DbBase.deleteImport(path)
                data.removeAt(adapterPosition)
                notifyItemRemoved(adapterPosition)
                clickAction.invoke(true,path)
            })
        }


    }


}