package com.ux.video.file.filerecovery.result

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.ux.video.file.filerecovery.base.BaseAdapter
import com.ux.video.file.filerecovery.databinding.ScanResultAdapterBinding
import com.ux.video.file.filerecovery.photo.ResultPhotos
import com.ux.video.file.filerecovery.photo.ResultPhotosFiles
import com.ux.video.file.filerecovery.utils.ExtendFunctions.dpToPx
import java.io.File

class ScanResultAdapter(
    mContext: Context,
    var onClickItem: (allFiles: ArrayList<ResultPhotosFiles>) -> Unit
) :
    BaseAdapter<ResultPhotos, ScanResultAdapterBinding>(mContext) {
    override fun getViewBinding(parent: ViewGroup): ScanResultAdapterBinding =
        ScanResultAdapterBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )

    @SuppressLint("SetTextI18n")
    override fun bindItem(
        holder: VHolder<ScanResultAdapterBinding>,
        item: ResultPhotos
    ) {

        holder.vb.run {

            val imageViews = listOf(im1, im2, im3)
            item.run {
                imageViewEnter.setOnClickListener { onClickItem(allFiles) }
                textDirNameCount.text = dirName
                textFileCounts.text = "(${allFiles.size})"
                val takeFiles = allFiles.take(3)
                imageViews.forEachIndexed { index, imageView ->
                    if (index < takeFiles.size) {
                        takeFiles[index].targetFile?.let {
                            loadImageView(mContext, it, imageView)
                        }
                    } else {
                        imageView.setImageDrawable(null)
                    }
                    imageView.setOnClickListener { onClickItem(allFiles) }

                }
            }
        }


    }

    private fun loadImageView(context: Context, file: File, imageView: ImageView) {
        Glide.with(context)
            .load(file)
            .apply(
                RequestOptions()
                    .transform(CenterCrop(), RoundedCorners(8.dpToPx(context)))
            )
            .into(imageView)
    }
}