package com.kdanmobile.reader.screen.reader.mediabox.stamp

import android.content.Context
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.kdanmobile.kmpdfkit.annotation.stamp.StampConfig
import com.kdanmobile.reader.R

class StandardStampAdapter(private val context: Context, private val resourceIds: Array<StampConfig.STANDARD_STAMP_RES>): RecyclerView.Adapter<StandardStampViewHolder>() {

    private var selectedIndex = 0
    private var onStampClickListener: OnStampClickListener? = null

    override fun onBindViewHolder(holder: StandardStampViewHolder, position: Int) {

        holder.imageView.setOnClickListener {
            if (position != selectedIndex) {
                val oldSelectedIndex = selectedIndex
                selectedIndex = position
                notifyItemChanged(selectedIndex)
                notifyItemChanged(oldSelectedIndex)
                onStampClickListener?.onStampClick(selectedIndex)
            }
        }
        holder.imageView.setImageResource(resourceIds[position].resId)
        holder.imageView.setBackgroundColor(when (position == selectedIndex) {
            true -> ContextCompat.getColor(context, R.color.mediaBox_standardStamp_selected)
            false -> ContextCompat.getColor(context, R.color.mediaBox_standardStamp_normal)
        })
    }

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

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

    fun setOnStampClickListener(onStampClickListener: OnStampClickListener?) {
        this.onStampClickListener = onStampClickListener
    }
}

class StandardStampViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
    val imageView: ImageView = itemView.findViewById(R.id.iv_mediaBoxStampStandard)
}