package com.yidian.yac.newscontent.template

import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.yidian.chameleon.ChameleonParser
import com.yidian.common.utils.ViewHolderUtil.Companion.createItemView
import com.yidian.yac.newscontent.R
import com.yidian.yac.newscontent.ui.NewsContentActivity
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.item_home_simple.*

/**
 * Author: hy
 * Date: 4/29/21
 * Description:
 */
class TemplateAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val dataList: ArrayList<TemplateItemBean> by lazy { ArrayList<TemplateItemBean>() }
    private lateinit var chameleonParser: ChameleonParser


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == 0) {
            ViewHolder(createItemView(parent, R.layout.item_home_simple))

        } else {
            ChameleonViewHolder(createChameleonView(parent, viewType))
        }

    }


    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun getItemViewType(position: Int): Int {
        return dataList[position].itemType
    }

    private fun createChameleonView(parent: ViewGroup, viewType: Int): View {
        if (!this::chameleonParser.isInitialized) {
            chameleonParser = ChameleonParser(parent.context)
        }
        //为了方便，此处viewType用作chameleonId
        return chameleonParser.createView(viewType.toString())
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        holder.itemView.setOnClickListener {
            it.context.startActivity(Intent(it.context, NewsContentActivity::class.java))
        }
        if (getItemViewType(position) == 0) {
            holder as ViewHolder
            holder.setData(dataList[position])
            return
        }
        holder as ChameleonViewHolder
        chameleonParser.bindTemplateData(holder.itemView, dataList[position].content)
    }


    fun setData(list: ArrayList<TemplateItemBean>?) {
        list?.let {
            dataList.clear()
            dataList.addAll(it)
            notifyDataSetChanged()
        }
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), LayoutContainer {
        override val containerView: View?
            get() = itemView

        @SuppressLint("SetTextI18n")
        fun setData(templateItemBean: TemplateItemBean) {
            tv_itemHomeName.text = "卡片 $adapterPosition ${templateItemBean.content}"
            tv_itemHomeContent.text = "Native 卡片"

        }
    }

    class ChameleonViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}