package com.bearya.kids.chapter

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import androidx.databinding.DataBindingUtil
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bearya.data.entity.Chapter
import com.bearya.kids.databinding.ItemChapterBinding
import library.OnItemClickListener
import library.ext.assetsPath

class ChapterAdapter : PagedListAdapter<Chapter, UnitViewHolder>(object : DiffUtil.ItemCallback<Chapter>() {

    override fun areItemsTheSame(oldItem: Chapter, newItem: Chapter): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: Chapter, newItem: Chapter): Boolean {
        return TextUtils.equals(oldItem.name, newItem.name) && oldItem.lock == newItem.lock
    }

}) {

    var onItemClickListener: OnItemClickListener<Chapter>? = null
    private var recyclerView: RecyclerView? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UnitViewHolder = UnitViewHolder(
            ItemChapterBinding.inflate(LayoutInflater.from(parent.context), parent, false).root
    )

    override fun onBindViewHolder(holder: UnitViewHolder, position: Int) {
        val item = getItem(position)
        holder.bindView?.name = item?.name
        holder.bindView?.cover = "chapter/${item?.name}/${item?.name}.webp".assetsPath()
        holder.itemView.apply {

            setOnClickListener {
                onItemClickListener?.invoke(it, item, position)
            }
            onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
                if (hasFocus) {
                    recyclerView?.smoothScrollToPosition(position)
                }
                val scale = if (hasFocus) 1.1f else 1.0f
                ViewCompat.animate(v).scaleX(scale).scaleY(scale).start()
            }
        }
    }

    override fun onDetachedFromRecyclerView(rv: RecyclerView) {
        super.onDetachedFromRecyclerView(rv)
        recyclerView = null
    }

    override fun onAttachedToRecyclerView(rv: RecyclerView) {
        super.onAttachedToRecyclerView(rv)
        recyclerView = rv
    }
}

class UnitViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    val bindView: ItemChapterBinding? = DataBindingUtil.bind(itemView)

}