package partisan.weforge.xyz.pulse

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class ContactAdapter(
    private val prefs: Preferences,
    private val fullList: List<ContactEntry>
) : RecyclerView.Adapter<ContactAdapter.ViewHolder>() {

    private var filteredList = fullList.toMutableList()

    inner class ViewHolder(inflater: LayoutInflater, parent: ViewGroup) :
        RecyclerView.ViewHolder(inflater.inflate(R.layout.item_contact, parent, false)) {
        val contactName: TextView = itemView.findViewById(R.id.contactName)
        val contactAllowed: CheckBox = itemView.findViewById(R.id.contactAllowed)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(parent.context), parent)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val contact = filteredList[position]
        holder.contactName.text = contact.name
        holder.contactAllowed.setOnCheckedChangeListener(null)
        holder.contactAllowed.isChecked = prefs.isContactWhitelisted(contact.phoneNumber)

        holder.contactAllowed.setOnCheckedChangeListener { _, isChecked ->
            prefs.setContactWhitelisted(contact.phoneNumber, isChecked)
        }
    }

    override fun getItemCount(): Int = filteredList.size

    fun filter(query: String) {
        filteredList = if (query.isBlank()) {
            fullList.toMutableList()
        } else {
            fullList.filter {
                it.name.contains(query, ignoreCase = true)
            }.toMutableList()
        }
        notifyDataSetChanged()
    }
}
