package com.base.easyfilemanager.adapter

import android.annotation.SuppressLint
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.base.easyfilemanager.R
import com.base.easyfilemanager.bean.FileCategoryBean
import com.base.easyfilemanager.databinding.ItemFileCategoryBinding
import com.base.easyfilemanager.databinding.ItemRecentMediaBinding
import com.base.easyfilemanager.view.XmlEx.inflate
import com.bumptech.glide.Glide

class FileCategoryAdapter(val mode: String = MODE_CATEGORY, val click: (key: String) -> Unit) :
    RecyclerView.Adapter<FileCategoryAdapter.DC>() {

    private val list = arrayListOf<FileCategoryBean>()


    class DC(view: View) : ViewHolder(view)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DC {
        return when (mode) {
            MODE_DOCUMENT -> DC(R.layout.item_file_category.inflate(parent))
            MODE_RECENT -> DC(R.layout.item_recent_media.inflate(parent))
            else -> DC(R.layout.item_file_category.inflate(parent))
        }
    }

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

    override fun onBindViewHolder(holder: DC, position: Int) {
        val context = holder.itemView.context
        val data = list[position]
        when (mode) {
            MODE_CATEGORY -> {
                val binding = ItemFileCategoryBinding.bind(holder.itemView)
                binding.iv.setImageResource(data.drawable)
                binding.tv.text = data.tittle
                binding.root.setOnClickListener {
                    click.invoke(data.key)
                }
            }

            MODE_RECENT -> {
                val binding = ItemRecentMediaBinding.bind(holder.itemView)
                Glide.with(context).load(data.url).centerCrop().into(binding.iv)
                binding.root.setOnClickListener {
                    click.invoke(data.key)
                }
            }
        }

    }

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

    companion object {
        val MODE_CATEGORY = "category"
        val MODE_DOCUMENT = "document"
        val MODE_MEDIA = "media"
        val MODE_RECENT = "recent"
    }
}
