package com.gh.gamecenter.qa.comment

import android.content.Context
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import androidx.core.util.forEach
import androidx.recyclerview.widget.RecyclerView
import com.facebook.drawee.view.SimpleDraweeView
import com.gh.gamecenter.ImageViewerActivity
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.databinding.ItemCommentPictureBinding
import com.lightgame.adapter.BaseRecyclerAdapter

class CommentPictureAdapter(val context: Context, var pictureList: ArrayList<String>, val entrance: String) :
    BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {

    private var countAndKey: Pair<Int, String>? = null
    private val mImageViewArray = SparseArray<SimpleDraweeView>()

    init {
        var dataIds = ""
        pictureList.forEach {
            dataIds += it
        }
        if (dataIds.isNotEmpty()) countAndKey = Pair(pictureList.size, dataIds)
    }

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

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is CommentPictureViewHolder) {
            val imageUrl = pictureList[position]
            ImageUtils.display(holder.binding.commentPicture, imageUrl)
            holder.binding.root.setOnClickListener {
                val imageViewList = ArrayList<View>()
                mImageViewArray.forEach { _, value ->
                    imageViewList.add(value)
                }
                val intent = ImageViewerActivity.getIntent(context, pictureList, position, imageViewList, entrance)
                context.startActivity(intent)
            }
            mImageViewArray.put(position, holder.binding.commentPicture)
        }
    }

    override fun getItemCount(): Int = pictureList.size

    fun checkResetData(update: ArrayList<String>) {
        var dataIds = ""
        update.forEach {
            dataIds += it
        }
        pictureList = update

        if (countAndKey?.first == update.size && countAndKey?.second != dataIds) {
            notifyItemRangeChanged(0, itemCount)
        } else if (countAndKey?.first != update.size) {
            notifyDataSetChanged()
        }

        // 重新刷新数据标识
        countAndKey = Pair(update.size, dataIds)
    }

    class CommentPictureViewHolder(val binding: ItemCommentPictureBinding) : RecyclerView.ViewHolder(binding.root)
}