package com.zxhy.simplefilesmanager.simpleadpter

import android.annotation.SuppressLint
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
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.zxhy.simplefilesmanager.R
import com.zxhy.simplefilesmanager.simpledata.JoFileJo
import com.zxhy.simplefilesmanager.simplejoke.DipPxEx

@SuppressLint("NotifyDataSetChanged")
abstract class JoCommonJoAdapter<T : ViewHolder, E : JoFileJo>() : RecyclerView.Adapter<T>() {

    val joFileList = arrayListOf<E>()

    fun bindIcon(data: JoFileJo, iv: ImageView) {
        val file = data.toFile()
        when {
            JoFileJo.isImage(file) or JoFileJo.isVideo(file) -> {
                val radius = DipPxEx.dp2px(iv.context, R.dimen.dp_5)
                val options =
                    RequestOptions().transform(
                        CenterCrop(), RoundedCorners(radius)
                    )

                Glide.with(iv.context)
                    .load(data.path)
                    .apply(options)
                    .into(iv)
            }
            JoFileJo.isAudio(file) -> iv.setImageResource(R.mipmap.sfaad_598)
            JoFileJo.isZip(file) -> iv.setImageResource(R.mipmap.sfz_6985)
            JoFileJo.isApk(file) -> iv.setImageResource(R.mipmap.vzxv_59875)
            JoFileJo.isDocument(file) -> iv.setImageResource(R.mipmap.szxv_8859)
            JoFileJo.isLargeFile(file) -> iv.setImageResource(R.mipmap.fasd_589256)

        }
    }

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

    fun setData(data: List<E>) {
        joFileList.clear()
        joFileList.addAll(data)
        notifyDataSetChanged()
    }

    fun addData(data: List<E>) {
        joFileList.addAll(data)
        notifyDataSetChanged()
    }

    fun clearData() {
        if (joFileList.size == 0) return
        joFileList.clear()
        notifyDataSetChanged()
    }

    fun removeData(data: List<E>) {
        data.forEach {
            val index = joFileList.indexOf(it)
            if (index != -1) {
                joFileList.removeAt(index)
                notifyItemRemoved(index)
            }
        }
    }

    fun getSelectData(): List<E> {
        return joFileList.filter { it.isSelected }
    }

    fun toggleSelect(select: Boolean) {
        joFileList.forEach { fileBean ->
            fileBean.isSelected = select
        }
        notifyDataSetChanged()
    }


}