package com.gh.gamecenter.forum.home

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.PagerAdapter
import com.facebook.drawee.view.SimpleDraweeView
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.RecyclingPagerAdapter
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.entity.ForumBannerEntity
import com.gh.gamecenter.login.user.UserManager

class ForumBannerAdapter(
    private val mContext: Context,
    private var mList: List<ForumBannerEntity>,
) : RecyclingPagerAdapter() {

    private var countAndKey: Pair<Int, String>? = null
    private var mIsInfiniteLoop = getDataSize() != 1

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

    private fun getDataSize() = mList.size

    fun getRealPosition(position: Int) =
        if (mIsInfiniteLoop) position % getDataSize() else position

    override fun getCount() = if (mIsInfiniteLoop) Int.MAX_VALUE else getDataSize()

    override fun getItemPosition(`object`: Any) = PagerAdapter.POSITION_NONE

    override fun getView(position: Int, convertView: View?, container: ViewGroup?): View {
        var view: View? = convertView
        if (convertView == null) {
            view = View.inflate(mContext, R.layout.forum_banner_item, null)
        }

        val index = getRealPosition(position)
        if (index >= getDataSize()) return view!!

        val banner = mList[index]
        val image = view!!.findViewById<SimpleDraweeView>(R.id.image)
        ImageUtils.display(image, banner.icon)

        view.setOnClickListener {
            val userId = UserManager.getInstance().userId
            DirectUtils.directToLinkPage(mContext, banner, "论坛banner", "")
            NewLogUtils.logClickBBSCarousel(banner.type ?: "", banner.link ?: "", index, userId)
        }

        return view
    }

    fun checkResetData(update: List<ForumBannerEntity>) {
        var dataIds = ""
        update.forEach {
            dataIds += it.icon
        }

        mList = update
        mIsInfiniteLoop = getDataSize() != 1

        if (countAndKey?.first != update.size || countAndKey?.second != dataIds) {
            notifyDataSetChanged()
        }

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