package com.mobiuz.app.dev.ui.auth.pin

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.mobiuz.app.R
import com.mobiuz.app.databinding.ItemPinBinding
import com.mobiuz.app.dev.model.PinData
import com.mobiuz.app.dev.utils.extensions.SingleBlock

class PinAdapter : RecyclerView.Adapter<PinAdapter.VHolder>() {

    private val list: ArrayList<PinData> by lazy { ArrayList() }
    private var listener: SingleBlock<String>? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VHolder {
        return VHolder(ItemPinBinding.inflate(LayoutInflater.from(parent.context)))
    }

    override fun onBindViewHolder(holder: VHolder, position: Int) = holder.bind(position)
    override fun getItemCount() = list.size

    inner class VHolder(private val binding: ItemPinBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(position: Int) {
            val d = list[position]
            binding.imagePin.setImageResource(if (d.count == -1) R.drawable.ic_pin_unchecked else R.drawable.ic_pin_checked)
        }
    }

    fun submitList(ls: List<PinData>) {
        list.clear()
        list.addAll(ls)
        notifyDataSetChanged()
    }

    fun addItem(id: Int) {
        val index = getAddItem()
        if (index != -1) {
            list[index].count = id
            notifyItemChanged(index)
            if (index == 3) checkDone()
        } else {
            list.forEach {
                it.count = -1
            }
            notifyDataSetChanged()
        }

    }

    private fun checkDone() {
        var pin = ""
        list.forEach {
            pin += it.count.toString()
        }
        if (pin.length == 4) {
            listener?.invoke(pin)
        }
    }

    fun removeItem() {
        val index = getCheckedItem()
        if (index != -1) {
            list[index].count = -1
            notifyItemChanged(index)
        }
    }

    private fun getCheckedItem(): Int {
        var pos = -1
        for (i in list.indices) {
            if (list[i].count != -1)
                pos = i
        }
        return pos
    }


    private fun getAddItem(): Int {
        var pos = -1
        for (i in list.indices) {
            if (list[i].count == -1) {
                pos = i
                return pos
            }
        }
        return pos
    }

    fun setOnDoneListener(block: SingleBlock<String>) {
        listener = block
    }

}



