package com.gh.gamecenter.forum.detail

import android.content.Context
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.databinding.ItemIconTabBinding
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.entity.ForumDetailEntity
import com.lightgame.adapter.BaseRecyclerAdapter

class ForumSectionAdapter(context: Context, val viewModel: ForumDetailViewModel, val onClick: (Int) -> Unit) :
    BaseRecyclerAdapter<ForumSectionAdapter.ForumSectionItemViewHolder>(context) {

    private var mSectionList = listOf<ForumDetailEntity.Section>()

    fun submitList(sectionList: List<ForumDetailEntity.Section>) {
        mSectionList = sectionList
        notifyItemRangeChanged(0, itemCount)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ForumSectionItemViewHolder =
        ForumSectionItemViewHolder(parent.toBinding())

    override fun getItemCount(): Int = mSectionList.size

    override fun onBindViewHolder(holder: ForumSectionItemViewHolder, position: Int) {
        val entity = mSectionList[position]
        holder.binding.iconIv.goneIf(entity.iconType.isEmpty() || entity.iconType == "none")
        when {
            entity.iconType == "url" && entity.icon.isNotEmpty() -> ImageUtils.display(
                holder.binding.iconIv,
                entity.icon
            )

            entity.iconType == "new" -> ImageUtils.display(holder.binding.iconIv, R.drawable.icon_section_newest)
            entity.iconType == "hot" -> ImageUtils.display(holder.binding.iconIv, R.drawable.icon_section_heat)
        }
        holder.binding.titleTv.run {
            text = entity.name
            setTextColor(
                if (entity.id == viewModel.selectedSection.id) com.gh.gamecenter.common.R.color.text_theme.toColor(mContext) else com.gh.gamecenter.common.R.color.text_secondary.toColor(
                    mContext
                )
            )
            setOnClickListener {
                viewModel.selectedSection = entity
                notifyItemRangeChanged(0, itemCount)
                onClick.invoke(position)
            }
        }
        holder.binding.root.run {
            layoutParams = (layoutParams as MarginLayoutParams).apply {
                leftMargin = if (position == 0) 16F.dip2px() else 6F.dip2px()
            }
            background =
                if (entity.id == viewModel.selectedSection.id) com.gh.gamecenter.common.R.drawable.button_round_theme_alpha_10.toDrawable(
                    mContext
                ) else com.gh.gamecenter.feature.R.drawable.button_round_gray_light.toDrawable(
                    mContext
                )
        }
    }

    class ForumSectionItemViewHolder(val binding: ItemIconTabBinding) : RecyclerView.ViewHolder(binding.root)
}