package com.gh.gamecenter.servers

import android.content.Context
import android.util.SparseArray
import android.view.ViewGroup
import androidx.annotation.Nullable
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.IExposable
import com.gh.common.util.DownloadItemUtils
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.databinding.ItemTestServerTextBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureEvent.Companion.createEvent
import com.gh.gamecenter.feature.exposure.ExposureSource
import com.gh.gamecenter.feature.game.GameItemViewHolder
import com.lightgame.adapter.BaseRecyclerAdapter

class GameServersTestAdapter(
    context: Context,
    private val mViewModel: GameServersTestViewModel,
    private val mScrollToTopClosure: () -> Unit,
    private var mBasicExposureSource: List<ExposureSource>?,
    private val mEntrance: String
) : BaseRecyclerAdapter<RecyclerView.ViewHolder>(context), IExposable {

    private var mDataList = ArrayList<GameServersTestViewModel.ItemData>()
    private val mExposureEventArray: SparseArray<ExposureEvent> = SparseArray()

    fun submitList(updateData: ArrayList<GameServersTestViewModel.ItemData>) {
        mDataList = updateData
        notifyDataSetChanged()
    }

    override fun getItemViewType(position: Int): Int {
        if (mDataList.size == position) {
            return GameServersContentAdapter.VIEW_TYPE_FOOTER
        }
        return when {
            mDataList[position].time != null -> GameServersContentAdapter.VIEW_TYPE_TOP

            mDataList[position].text != null -> ItemViewType.ITEM_EMPTY

            else -> GameServersContentAdapter.VIEW_TYPE_ITEM
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            GameServersContentAdapter.VIEW_TYPE_FOOTER -> {
                FooterViewHolder(mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false))
            }
            GameServersContentAdapter.VIEW_TYPE_TOP -> {
                GameServerTimeViewHolder(parent.toBinding())
            }
            ItemViewType.ITEM_EMPTY -> {
                TextViewHolder(parent.toBinding())
            }
            else -> {
                GameItemViewHolder(parent.toBinding())
            }
        }
    }

    override fun getItemCount() = if (mDataList.size == 0) 0 else mDataList.size + 1

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is GameItemViewHolder -> {
                val gameEntity = mDataList[position].game!!
                val exposureSources = ArrayList<ExposureSource>()
                val isTheLastOfTheLatestConsecutiveGame = mDataList[position].isTheLastOfTheLatestConsecutiveGame

                holder.itemView.setPadding(
                    16F.dip2px(),
                    8F.dip2px(),
                    16F.dip2px(),
                    if (isTheLastOfTheLatestConsecutiveGame) 16F.dip2px() else 8F.dip2px()
                )

                holder.bindGameItem(gameEntity, forceShowSubtitle = true)

                mBasicExposureSource?.let { exposureSources.addAll(it) }

                exposureSources.add(
                    ExposureSource(
                        "开测表详情",
                        getExposureSourceValue(gameEntity.testTime ?: "")
                    )
                )

                mExposureEventArray.put(position, createEvent(gameEntity, exposureSources))
                initViewHolder(gameEntity, holder)
            }
            is GameServerTimeViewHolder -> {
                holder.binding.root.setBackgroundColor(R.color.background_white.toColor(mContext))
                holder.binding.kaifuItemTimeTv.setTextColor(R.color.text_title.toColor(mContext))
                holder.binding.kaifuItemHeader.setImageResource(R.drawable.kaifu_time_icon)
                holder.binding.kaifuItemTimeTv.text = mDataList[position].time
            }
            is FooterViewHolder -> {
                initFooterViewHolder(holder)
            }
            is TextViewHolder -> {
                holder.binding.root.setBackgroundColor(R.color.background_white.toColor(mContext))
                holder.binding.contentTv.text = mDataList[position].text
            }
        }
    }

    private fun initViewHolder(gameEntity: GameEntity, viewHolder: GameItemViewHolder) {
        DownloadItemUtils.setOnClickListener(
            mContext,
            viewHolder.binding.downloadBtn, gameEntity, viewHolder.adapterPosition, this,
            StringUtils.buildString(mEntrance, "+(开服表[", viewHolder.adapterPosition.toString(), "])"),
            StringUtils.buildString("开服表:", gameEntity.name),
            mExposureEventArray[viewHolder.adapterPosition]
        )
        DownloadItemUtils.updateItem(
            mContext,
            gameEntity,
            GameViewHolder(viewHolder.binding),
            true,
            gameEntity.briefStyle
        )
        viewHolder.itemView.setOnClickListener {
            GameDetailActivity.startGameDetailActivity(
                mContext, gameEntity,
                StringUtils.buildString(mEntrance, "+(开服表[", viewHolder.adapterPosition.toString(), "])"),
                traceEvent = mExposureEventArray[viewHolder.adapterPosition]
            )
        }
    }

    private fun initFooterViewHolder(viewHolder: FooterViewHolder) {
        viewHolder.initFooterViewHolder(false, false, true, R.string.load_over_with_click_hint) {
            mScrollToTopClosure.invoke()
        }
    }

    private fun getExposureSourceValue(testTime: String): String {
        val sb = StringBuilder()
        sb.append(mViewModel.testTitle)
        if (!mViewModel.getTestEntity()?.remark.isNullOrEmpty()) {
            sb.append("-")
            sb.append(mViewModel.getTestEntity()?.remark)
        }
        sb.append("+")
        sb.append(mViewModel.getCurrentTimeFilter())
        sb.append("+")
        sb.append(mViewModel.getCurrentTypeFilter())
        sb.append("+")
        sb.append(testTime)
        return sb.toString()
    }

    @Nullable
    override fun getEventByPosition(pos: Int): ExposureEvent? {
        return mExposureEventArray[pos]
    }

    @Nullable
    override fun getEventListByPosition(pos: Int): List<ExposureEvent>? = null

    class TextViewHolder(var binding: ItemTestServerTextBinding) : RecyclerView.ViewHolder(binding.root)

}