package de.sebse.fuplanner2.ui.details_announcements

import android.view.ViewGroup
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import de.sebse.fuplanner2.database.Announcement
import de.sebse.fuplanner2.ui.ListItemHolder
import de.sebse.fuplanner2.utils.toDateTimeString

class AnnouncementsAdapter() : PagedListAdapter<Announcement, 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.createdOn.toDateTimeString(actCtx)
            holder.subRight.text = it.createdBy
        } ?: run {
            holder.clear()
            holder.itemView.setOnClickListener(null)
        }
    }
}

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

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

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