package com.webtoonviewer.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.webtoonviewer.R
import com.webtoonviewer.ui.data.TitleItem
import com.webtoonviewer.utils.CommonUtils.getEllipsizedText
import com.webtoonviewer.utils.CommonUtils.getShortNameFromEpisode
import com.webtoonviewer.utils.loadImgFromAssets

class TitleAdapter(
    private val context: Context,
    private val titleItems: MutableList<TitleItem>,
    private val onItemClick: OnItemClickListener
) : RecyclerView.Adapter<TitleItemViewHolder>() {

    interface OnItemClickListener {
        fun clickToEpisodeList(titleItem: TitleItem)
        fun clickToSingleEpisode(titleItem: TitleItem)
    }

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

    override fun onBindViewHolder(holder: TitleItemViewHolder, position: Int) {
        val titleItem = titleItems[position]

        val bitmap = loadImgFromAssets(context, titleItem.thumbnail)
        if (bitmap != null) {
            holder.thumbnail.setImageBitmap(bitmap)
        } else {
            holder.thumbnail.setImageResource(R.drawable.ic_launcher_background)
        }

        holder.title.text = titleItem.title
        holder.tag.text = titleItem.tag
        val chapterTextView = holder.chapter
        if (titleItem.chapter != "") {
            chapterTextView.post{
                chapterTextView.text = getEllipsizedText(chapterTextView, "${getShortNameFromEpisode(titleItem.chapter)} >>")
            }
        }

        holder.thumbnail.setOnClickListener {
            onItemClick.clickToEpisodeList(titleItem)
        }

        holder.title.setOnClickListener {
            onItemClick.clickToEpisodeList(titleItem)
        }

        holder.tag.setOnClickListener {
            onItemClick.clickToEpisodeList(titleItem)
        }

        holder.chapter.setOnClickListener {
            onItemClick.clickToSingleEpisode(titleItem)
        }
    }

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

    fun updateItem(titleItem: TitleItem) {
        val index = titleItems.indexOf(titleItem)
        notifyItemChanged(index)
    }
}
