package com.gh.gamecenter.personalhome.home.game

import android.content.Context
import android.graphics.Color
import android.util.SparseBooleanArray
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.common.util.*
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.ItemUserCommentHistoryBinding
import com.gh.gamecenter.gamedetail.rating.RatingReplyActivity
import com.gh.gamecenter.gamedetail.rating.edit.RatingEditActivity
import com.gh.gamecenter.personalhome.rating.MyRating
import java.util.regex.Pattern

class UserCommentHistoryAdapter(
    context: Context,
    private val mEntrance: String,
    private val mFragment: Fragment,
    private val mListViewModel: UserCommentHistoryViewModel
) : ListAdapter<MyRating>(context) {

    private var mExpandSparseBooleanArray = SparseBooleanArray()


    override fun getItemCount(): Int {
        return if (mEntityList == null || mEntityList.isEmpty()) return 0 else mEntityList.size + 1
    }

    override fun getItemViewType(position: Int): Int {
        if (position == itemCount - 1) {
            return ItemViewType.ITEM_FOOTER
        }
        return ItemViewType.ITEM_BODY
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.ITEM_BODY -> {
                UserCommentHistoryItemViewHolder(parent.toBinding())
            }
            else -> {
                FooterViewHolder(mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false))
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is UserCommentHistoryItemViewHolder -> {
                val marginTop = if (position == 0) 8F.dip2px() else 16F.dip2px()
                holder.binding.gameInfo.layoutParams =
                    (holder.binding.gameInfo.layoutParams as ViewGroup.MarginLayoutParams).apply {
                        setMargins(0, marginTop, 0, 0)
                    }

                var isChildLongClick = false
                val rating = mEntityList[position]
                holder.binding.gameName.text = rating.game.name
                holder.binding.amwayScoreNumber.text = if (rating.game.star > 0) rating.game.star.toString() else "评分过少"
                holder.binding.amwayScoreNumber.setTextColor(Color.parseColor(if (rating.game.star > 0) "#1383EB" else "#2496FF"))
                holder.binding.ratingStart.rating = rating.star.toFloat()
                holder.binding.comment.text = if (rating.reply > 0) NumberUtils.transSimpleCount(rating.reply) else ""
                holder.binding.vote.isChecked = rating.me.isVoted
                holder.binding.vote.text = if (rating.vote > 0) NumberUtils.transSimpleCount(rating.vote) else ""
                CommentUtils.setCommentTime(holder.binding.timeTv, rating.time)

                holder.binding.divider.visibility = if (position == 0) View.GONE else View.VISIBLE

                val maxDesLines = if (mExpandSparseBooleanArray.get(holder.adapterPosition)) Int.MAX_VALUE else 3
                holder.binding.tvComment.setExpandMaxLines(maxDesLines)
                holder.binding.tvComment.setIsExpanded(Int.MAX_VALUE == maxDesLines)

                holder.binding.gameIcon.displayGameIcon(
                    rating.game.getRawIconIfExisted(),
                    rating.game.iconSubscript,
                    rating.game.iconFloat
                )

                val m = Pattern.compile(RatingEditActivity.LABEL_REGEX).matcher(rating.content)
                if (m.find()) {
                    val contents = TextHelper.getCommentLabelSpannableStringBuilder(rating.content, R.color.theme_font)
                    holder.binding.tvComment.setTextWithHighlightedTextWrappedInsideWrapper(
                        text = contents,
                        copyClickedText = true
                    )
                } else {
                    holder.binding.tvComment.setTextWithHighlightedTextWrappedInsideWrapper(
                        text = rating.content,
                        copyClickedText = true
                    )
                }
                holder.binding.tvComment.setExpandCallback {
                    mExpandSparseBooleanArray.put(holder.adapterPosition, true)
                }

                holder.binding.vote.setOnClickListener {
                    if (mEntrance == "我的发布") {
                        NewFlatLogUtils.logHaloSelfPublishContent("评论", "卡片内容")
                    }
                    mContext.ifLogin(mEntrance) {
                        if (!holder.binding.vote.isChecked) {
                            mListViewModel.voteComment(rating.game.id, rating.id, callback = {
                                val count = rating.vote + 1
                                holder.binding.vote.text = count.toString()
                                holder.binding.vote.isChecked = true
                                rating.vote = count
                                rating.me.isVoted = true
                            })
                        } else {
                            mListViewModel.unVoteComment(rating.game.id, rating.id, callback = {
                                val count = rating.vote - 1
                                holder.binding.vote.text = if (count == 0) "" else count.toString()
                                holder.binding.vote.isChecked = false
                                rating.vote = count
                                rating.me.isVoted = false
                            })
                        }
                    }
                }

                holder.binding.apply {
                    gameInfo.setOnClickListener {
                        if (mEntrance == "我的发布") {
                            NewFlatLogUtils.logHaloSelfPublishContent("评论", "卡片内容")
                        }
                        MtaHelper.onEvent("我的光环_新", "我的游戏评论", "游戏详情")
                        DirectUtils.directToGameDetail(mContext, rating.game.id, "我的游戏评论")
                    }
                    commentInfo.setOnClickListener {
                        if (mEntrance == "我的发布") {
                            NewFlatLogUtils.logHaloSelfPublishContent("评论", "卡片内容")
                        }
                        if (isChildLongClick) {
                            isChildLongClick = false
                            return@setOnClickListener
                        }
                        MtaHelper.onEvent("我的光环_新", "我的游戏评论", "评论详情")
                        val intent =
                            RatingReplyActivity.getIntent(mContext, rating.game.id, rating.id, false, "我的游戏评论", "")

                        SyncDataBetweenPageHelper.startActivityForResult(mFragment, intent, 100, position)
                    }
                    tvComment.setOnLongClickListener(View.OnLongClickListener {
                        isChildLongClick = true
                        rating.content.replace(RatingEditActivity.LABEL_REPLACE_REGEX.toRegex(), "").copyTextAndToast()
                        return@OnLongClickListener true
                    })
                }
            }

            is FooterViewHolder -> {
                holder.initItemPadding()
                holder.initFooterViewHolder(mIsLoading, mIsNetworkError, mIsOver)
            }
        }
    }

    inner class UserCommentHistoryItemViewHolder(val binding: ItemUserCommentHistoryBinding) :
        BaseRecyclerViewHolder<Any>(binding.root)
}