package cz.muni.sutralog.ui.list

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import androidx.recyclerview.widget.RecyclerView
import cz.muni.sutralog.data.CategoryPresentableListItem
import cz.muni.sutralog.databinding.CategoryItemListBinding

class CategoryAdapter(private val onItemClick: (CategoryPresentableListItem) -> Unit,
) : RecyclerView.Adapter<CategoryViewHolder>(), Filterable {

    private var listItems: MutableList<CategoryPresentableListItem> = mutableListOf()
    private var fullListItems: MutableList<CategoryPresentableListItem> = mutableListOf()
    private var categoryFilter : Filter = object: Filter(){
        override fun performFiltering(constraint: CharSequence?): FilterResults {
            val filteredList = mutableListOf<CategoryPresentableListItem>()

            if (constraint == null || constraint.length == 0){
                filteredList.addAll(fullListItems)
            } else {
                val filterString: String = constraint.toString().lowercase().trim()

                for ( category in fullListItems ){
                    if(category.name.lowercase().contains(filterString)){
                        filteredList.add(category)
                    }
                }
            }
            val results = FilterResults()
            results.values = filteredList

            return results
        }

        override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
            listItems.clear()
            listItems.addAll(results?.values as Collection<CategoryPresentableListItem>)
            notifyDataSetChanged()
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder {
        val binding = CategoryItemListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return CategoryViewHolder(binding)
    }

    override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
        holder.bind(listItems[position], onItemClick)
    }

    fun submitList(newListItems: List<CategoryPresentableListItem>) {
        fullListItems = newListItems.toMutableList()
        listItems = fullListItems.toMutableList()
        notifyDataSetChanged()
    }

    fun removeItem(position: Int) {
        listItems.removeAt(position)
        notifyItemRemoved(position)
    }


    override fun getItemCount(): Int = listItems.size
    override fun getFilter(): Filter {
        return categoryFilter
    }
}
