package app.furmeet.events.brasilfurfest.schedule.adapters

import android.content.res.ColorStateList
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import com.adlerosn.brasilfurfest.R
import app.furmeet.events.brasilfurfest.helper.ListDiffCallback
import app.furmeet.events.brasilfurfest.helper.inflate
import app.furmeet.events.brasilfurfest.helper.layoutInflater
import app.furmeet.events.brasilfurfest.helper.solved
import app.furmeet.events.brasilfurfest.schedule.abstractDataTypes.convention.FilterableNamedColoredAttribute
import app.furmeet.events.brasilfurfest.schedule.viewHolders.RecyclerViewHolder
import kotlinx.android.synthetic.main.activity_search_filter_circle.view.*
import kotlinx.android.synthetic.main.activity_search_filter_criteria_itemdialog.view.*

class FilterCriteriaRecyclerViewAdapter<T : FilterableNamedColoredAttribute>(
        initialData: List<Pair<T?, () -> Any?>>,
        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()
                    }
                }
            }
    )

    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.tag_label.text = item.first.names.solved
        view.tag_color.imageTintList = ColorStateList.valueOf(item.first.color)
        view.setOnClickListener { item.second() }
    }

}
