package de.sebse.fuplanner2.ui.details_events

import android.view.ViewGroup
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import de.sebse.fuplanner2.database.Event
import de.sebse.fuplanner2.ui.*
import de.sebse.fuplanner2.utils.console
import de.sebse.fuplanner2.utils.toDateTimeString

class EventsAdapter() : PagedListAdapter<Event, ListItemHolder>(EventDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListItemHolder {
        return ListItemHolder.invoke(parent)
    }

    override fun onBindViewHolder(holder: ListItemHolder, position: Int) {
        val event = getItem(position)
        val actCtx = holder.itemView.context

        event?.let {
            holder.title.text = it.title
            holder.subLeft.text = it.startDateTime.toDateTimeString(actCtx)
            holder.subRight.text = it.location
        } ?: run {
            holder.clear()
            holder.itemView.setOnClickListener(null)
        }
    }
}

class EventDiffCallback : DiffUtil.ItemCallback<Event>() {

    override fun areItemsTheSame(oldItem: Event, newItem: Event): Boolean {
        return oldItem.uid == newItem.uid
    }

    override fun areContentsTheSame(oldItem: Event, newItem: Event): Boolean {
        return oldItem.getHash() == newItem.getHash()
    }
}