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

import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import android.widget.ImageView
import com.kdanmobile.kmpdfkit.annotation.stamp.StampConfig
import com.kdanmobile.reader.R
import android.widget.LinearLayout

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 view = ImageView(context)
        return StandardStampViewHolder(view)
    }

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

class StandardStampViewHolder(val imageView: ImageView): RecyclerView.ViewHolder(imageView) {
    init {
        val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        params.setMargins(8, 8, 8, 8)
        imageView.layoutParams = params
    }
}