package com.webtoonviewer.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.webtoonviewer.R
import com.webtoonviewer.utils.CommonUtils.getEllipsizedText
import com.webtoonviewer.utils.CommonUtils.getShortNameFromEpisode

class EpisodeAdapter(
    private val chapters: MutableList<String>,
    private val onItemClick: (String) -> Unit
) : RecyclerView.Adapter<EpisodeAdapter.ViewHolder>() {

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val chapterTextView: TextView = itemView.findViewById(R.id.tvItem)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_text, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val chapterTextView: TextView = holder.chapterTextView
        chapterTextView.post {
//            chapterTextView.text = getEllipsizedText(chapterTextView, chapters[position].split(".")[1])
            chapterTextView.text = getEllipsizedText(chapterTextView, getShortNameFromEpisode(chapters[position]))
        }

        holder.itemView.setOnClickListener {
            onItemClick(chapters[position])
        }
    }

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

}