package com.base.filerecoveryrecyclebin.adapter

import android.annotation.SuppressLint
import android.os.Build
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.base.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.activity.recyclebin.MyFileObserver.Companion.findRecycleBinFile
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean
import com.base.filerecoveryrecyclebin.databinding.ItemRecyclebinFileBinding
import com.base.filerecoveryrecyclebin.help.KotlinExt.toFormatSize
import com.base.filerecoveryrecyclebin.help.KotlinExt.toFormatTime
import com.base.filerecoveryrecyclebin.view.XmlEx.inflate
import com.bumptech.glide.Glide
import java.io.File

class RecycleBinAdapter(val click: (bean: RecycleBinBean) -> Unit) : RecyclerView.Adapter<RecycleBinAdapter.RBAV>() {

    private val beanList = arrayListOf<RecycleBinBean>()


    inner class RBAV(view: View) : ViewHolder(view) {

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RBAV {
        return RBAV(R.layout.item_recyclebin_file.inflate(parent))
    }

    override fun getItemCount(): Int {
        return beanList.size
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: RBAV, position: Int) {
        val binding = ItemRecyclebinFileBinding.bind(holder.itemView)
        val bean = beanList[position]
        val file = File(bean.path)
        val binFile = findRecycleBinFile(file.name)
        val context = holder.itemView.context
        Glide.with(context).load(binFile?.absoluteFile).centerCrop().into(binding.iv)
        binding.tvName.text = file.name
        binding.tvTime.text = "delete time:" + bean.deleteTime.toFormatTime()
        binding.tvSize.text = bean.size.toFormatSize()
        binding.root.setOnClickListener {
            click.invoke(bean)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setData(list: List<RecycleBinBean>) {
        beanList.clear()
        beanList.addAll(list)
        notifyDataSetChanged()
    }
}