package com.gh.gamecenter.feature.selector

import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.baselist.DiffUtilAdapter
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.selector.databinding.ItemLocalMediaPreviewQuickSelectBinding
import java.util.ArrayList

internal class QuickSelectAdapter(
    context: Context,
    private val viewModel: LocalMediaPreviewViewModel
) : DiffUtilAdapter<SelectedPreviewData>(context) {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): RecyclerView.ViewHolder {
        return ItemViewHolder(parent.toBinding())
    }

    override fun onBindViewHolder(
        holder: RecyclerView.ViewHolder,
        position: Int
    ) {
        val item = mDataList[position]

        if (holder is ItemViewHolder) {
            holder.bindView(item)
            holder.binding.root.setOnClickListener {
                if (item.item.positionInAlbum == -1) return@setOnClickListener

                val targetPosition = if (viewModel.isSelectedOnly()) {
                    viewModel.findPositionInSelectedSnapshotList(item.item.contentUri)
                } else {
                    if (item.item.positionInAlbum != -1) {
                        item.item.positionInAlbum
                    } else {
                        0
                    }
                }

                viewModel.scrollToPosition(targetPosition)
            }
        }
    }

    override fun getItemCount() = mDataList.size

    override fun areItemsTheSame(oldItem: SelectedPreviewData?, newItem: SelectedPreviewData?): Boolean {
        return oldItem?.item?.contentUri == newItem?.item?.contentUri
    }

    override fun areContentsTheSame(oldItem: SelectedPreviewData?, newItem: SelectedPreviewData?): Boolean {
        return oldItem?.isHighlighted == newItem?.isHighlighted
                && oldItem?.item?.contentUri == newItem?.item?.contentUri
    }

    private class ItemViewHolder(var binding: ItemLocalMediaPreviewQuickSelectBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bindView(item: SelectedPreviewData) {
            ImageUtils.displayResizeMedia(binding.thumbnailIv, item.item.contentUri, 56, 56)

            binding.selectedRingView.goneIf(!item.isHighlighted)
        }
    }
}