package com.bassbooster.soundeffects.equalizer.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.bassbooster.equalizer.R
import com.bassbooster.soundeffects.equalizer.data.model.AppMedia


class ChooseAppAdapter(
    private val apps: ArrayList<AppMedia>, val onItemClicked:(String) -> Unit
) : RecyclerView.Adapter<ChooseAppAdapter.DataViewHolder>() {

    class DataViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(app: AppMedia) {
            itemView.findViewById<ImageView>(R.id.imageViewAvatar).setImageBitmap(app.avatar)
            itemView.findViewById<TextView>(R.id.textViewName).text = app.name
            itemView.findViewById<ImageView>(R.id.ivCheck).isVisible = app.check
            if(app.check){
                itemView.setBackgroundResource(R.drawable.custom_image_nation_red)
            }else{
                itemView.setBackgroundResource(R.drawable.dra_custom_layout_play)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        DataViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.item_app, parent,
                false
            )
        )

    override fun getItemCount(): Int = apps.size

    @SuppressLint("NotifyDataSetChanged")
    override fun onBindViewHolder(holder: DataViewHolder, position: Int) {
        holder.bind(apps[position])
        holder.itemView.setOnClickListener{
            resetCheck()
            apps[position].check = true
            notifyDataSetChanged()
            onItemClicked(apps[position].packageName)
        }
    }
    private fun resetCheck(){
        for (item in this.apps){
            item.check = false
        }
    }

    fun addData(list: List<AppMedia>) {
        apps.addAll(list)
    }
}
