package app.furmeet.events.system.schedule.adapters

import android.content.res.ColorStateList
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import app.furmeet.events.bff.R
import app.furmeet.events.system.helper.ListDiffCallback
import app.furmeet.events.system.helper.inflate
import app.furmeet.events.system.helper.layoutInflater
import app.furmeet.events.system.helper.solved
import app.furmeet.events.system.schedule.abstractDataTypes.convention.FilterableNamedColoredAttribute
import app.furmeet.events.system.schedule.viewHolders.RecyclerViewHolder

class FilterCriteriaRecyclerViewAdapter<T : FilterableNamedColoredAttribute>(
    initialData: List<Pair<T?, () -> Any?>>,
    private val backgroundColor: Int?,
    private val displayChooser: () -> Any?
) : RecyclerViewAdapter() {
    private var dataset = initialData.toList()

    fun onDataChanged(newData: List<Pair<T?, () -> Any?>>) {
        val diff = DiffUtil.calculateDiff(
                ListDiffCallback(
                        dataset.map { it.first },
                        newData.map { it.first }
                )
        )
        dataset = newData.toList()
        diff.dispatchUpdatesTo(this)
    }

    override fun getItemCount(): Int = dataset.size

    override fun getItemViewType(position: Int) = if (dataset[position].first != null) 0 else 1

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = RecyclerViewHolder(
            parent.context.layoutInflater.inflate(
                    if (viewType == 0)
                        R.layout.activity_search_filter_criteria_item
                    else
                        R.layout.activity_search_filter_criteria_add
            ).apply {
                if (viewType == 1) {
                    setOnClickListener {
                        displayChooser()
                    }
                }
                backgroundColor?.let {
                    this.findViewById<View>(R.id.bkgInner).backgroundTintList = ColorStateList.valueOf(it)
                    this.findViewById<View>(R.id.bkgOuter).backgroundTintList = ColorStateList.valueOf(it)
                }
            }
    )

    override fun onBindViewHolder(viewHolder: RecyclerViewHolder, position: Int) {
        if (getItemViewType(position) == 1) return
        val view = viewHolder.itemView
        val item = dataset[position].let { Pair(it.first!!, it.second) }
        view.findViewById<TextView>(R.id.tag_label).text = item.first.names.solved
        view.findViewById<ImageView>(R.id.tag_color).imageTintList = ColorStateList.valueOf(item.first.color)
        view.setOnClickListener { item.second() }
    }

}
