package com.keyboard.craft.adapter

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.keyboard.craft.activity.CategoryDetailsActivity
import com.keyboard.craft.activity.CategoryDetailsActivity.Companion.CATEGORY_DETAILS_BEAN_KEY
import com.keyboard.craft.bean.MainDataBean
import com.keyboard.craft.databinding.MainRvItemBinding

class HomeDataAdapter(private val context: Context, private val mainDataList: List<MainDataBean>) :
    RecyclerView.Adapter<HomeDataAdapter.MainDataViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainDataViewHolder {
        val binding = MainRvItemBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return MainDataViewHolder(binding)
    }

    override fun onBindViewHolder(holder: MainDataViewHolder, position: Int) {
        val currentItem = mainDataList[position]
        holder.bind(currentItem)
    }

    override fun getItemCount() = mainDataList.size

    inner class MainDataViewHolder(private val binding: MainRvItemBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(mainData: MainDataBean) {
            binding.titleTextView.text = mainData.title
            val adapter = KeyItemDataAdapter(context, mainData.items!!)
            binding.itemRv.layoutManager =
                LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            binding.itemRv.adapter = adapter

            binding.moreData.setOnClickListener {
                val intent = Intent(context, CategoryDetailsActivity::class.java)
                intent.putExtra(CATEGORY_DETAILS_BEAN_KEY, mainData)
                context.startActivity(intent)
            }
        }
    }
}
