package com.base.superfilemanager.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.superfilemanager.R
import com.base.superfilemanager.bean.FileCategoryBean
import com.base.superfilemanager.databinding.ItemFileCategoryDocBinding
import com.base.superfilemanager.databinding.ItemFileCategoryMediaBinding
import com.base.superfilemanager.databinding.ItemRecentMediaBinding
import com.base.superfilemanager.view.XmlEx.inflate
import com.bumptech.glide.Glide

class FileCategoryAdapter(val mode: String, 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_doc.inflate(parent))
            MODE_MEDIA -> DC(R.layout.item_file_category_media.inflate(parent))
            MODE_RECENT -> DC(R.layout.item_recent_media.inflate(parent))
            else -> DC(R.layout.item_file_category_doc.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_DOCUMENT -> {
                val binding = ItemFileCategoryDocBinding.bind(holder.itemView)
                binding.iv.setImageResource(data.drawable)
                binding.tv.text = data.tittle
                binding.root.setOnClickListener {
                    click.invoke(data.key)
                }
            }

            MODE_MEDIA -> {
                val binding = ItemFileCategoryMediaBinding.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_DOCUMENT = "document"
        val MODE_MEDIA = "media"
        val MODE_RECENT = "recent"
    }
}
