package com.adealink.weparty.profile.ui.about.adapter

import android.text.SpannableStringBuilder
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.DrawableRes
import com.adealink.frame.aab.util.getCompatDrawable
import com.adealink.frame.ext.findAndSetSpan
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.recycleview.adapter.BindingViewHolder
import com.adealink.weparty.commonui.recycleview.adapter.multitype.ItemViewBinder
import com.adealink.weparty.commonui.widget.CenterImageSpan
import com.adealink.weparty.profile.databinding.LayoutProfileIntroduceBinding
import com.adealink.weparty.profile.ui.about.data.IntroduceItemData
import com.adealink.weparty.R as APP_R

class IntroduceViewBinder :
    ItemViewBinder<IntroduceItemData, IntroduceViewBinder.ViewHolder>() {

    override fun onBindViewHolder(
        holder: ViewHolder,
        item: IntroduceItemData,
    ) {
        holder.update(item)
    }

    override fun onCreateViewHolder(
        inflater: LayoutInflater,
        parent: ViewGroup,
    ): ViewHolder {
        return ViewHolder(
            LayoutProfileIntroduceBinding.inflate(
                inflater,
                parent,
                false
            )
        )
    }

    class ViewHolder(
        rootBinding: LayoutProfileIntroduceBinding,
    ) : BindingViewHolder<LayoutProfileIntroduceBinding>(rootBinding) {
        fun update(item: IntroduceItemData) {
            val userInfo = item.userInfo
            val languages = userInfo.languageNames?.joinToString(separator = "/")
            if (languages.isNullOrEmpty()) {
                binding.clLanguage.gone()
            } else {
                binding.clLanguage.show()
                binding.tvLanguage.text =
                    getSpanText(APP_R.drawable.common_language_ic, languages)
            }

            if (userInfo.intro.isNullOrEmpty()) {
                binding.clIntroduce.gone()
            } else {
                binding.clIntroduce.show()
                binding.tvIntroduce.text =
                    getSpanText(APP_R.drawable.common_introduce_ic, userInfo.intro)
            }
        }

        private fun getSpanText(
            @DrawableRes drawableId: Int,
            text: String?
        ): SpannableStringBuilder {
            val testStr = "[icon] ${text ?: ""}"
            return SpannableStringBuilder(testStr).apply {
                findAndSetSpan(
                    CenterImageSpan(getCompatDrawable(drawableId).apply {
                        setBounds(0, 0, 16.dp(), 16.dp())
                    }),
                    "[icon]"
                )
            }
        }
    }


}