package com.aaron.kakao.hospitalmapfortube.ui.main

import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.aaron.kakao.hospitalmapfortube.R
import com.aaron.kakao.hospitalmapfortube.data.remote.model.Document
import com.aaron.kakao.hospitalmapfortube.databinding.ItemLocationBinding
import com.aaron.kakao.hospitalmapfortube.ui.BindingViewHolder

/**
 * Created by aaron on 2020-03-30
 */
class LocationAdapter : RecyclerView.Adapter<BindingViewHolder<ItemLocationBinding>>() {
    // 콜백 프로퍼티
    lateinit var itemClickEvent: (Int) -> Unit

    private var newLocationList: MutableList<Document> = mutableListOf()
    var locationList: MutableList<Document> = mutableListOf()

    fun setData(newData: MutableList<Document>, isMore: Boolean) {
        if (!isMore) {
            newLocationList.clear()
        }
        newLocationList.addAll(newData)
        val diffCallback = LocationDiffCallback(locationList, newLocationList)
        val diffResult = DiffUtil.calculateDiff(diffCallback)

        locationList.clear()
        locationList.addAll(newLocationList)
        diffResult.dispatchUpdatesTo(this)
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): BindingViewHolder<ItemLocationBinding> {
        return LocationViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.item_location,
                parent,
                false
            )
        )
    }

    override fun getItemCount() = locationList.size

    override fun onBindViewHolder(holder: BindingViewHolder<ItemLocationBinding>, position: Int) {
        holder.binding?.locationData = locationList[position]
        holder.binding?.executePendingBindings()
    }

    inner class LocationViewHolder(itemView: View) :
        BindingViewHolder<ItemLocationBinding>(itemView) {
        init {
            binding?.itemLayout?.setOnClickListener {
                itemClickEvent(locationList[adapterPosition].id.toInt())
            }
        }
    }

    private class LocationDiffCallback(
        val oldList: List<Document>,
        val newList: List<Document>
    ) : DiffUtil.Callback() {
        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
            oldList[oldItemPosition].id == newList[newItemPosition].id

        override fun getOldListSize() = oldList.size

        override fun getNewListSize() = newList.size

        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
            oldList[oldItemPosition].phone == newList[newItemPosition].phone
    }
}