package com.proyek.akhir.kodel.ui.koperasi.beranda.jatuhtempo

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.proyek.akhir.kodel.R
import com.proyek.akhir.kodel.data.response.UtangItem
import kotlinx.android.synthetic.main.item_penunggak_pengingat.view.*
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

class JatuhTempoAdapter(private val listJatuhTempo: List<UtangItem>) :
    RecyclerView.Adapter<JatuhTempoAdapter.JatuhTempoViewHolder>() {

    inner class JatuhTempoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(item: UtangItem) {
            with(itemView) {
                Glide.with(itemView)
                    .load(item.fotoDiriAnggota)
                    .into(imgPenunggak)
                namePenunggak.text = item.namaAnggota
                val inputFormatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US)
                val datePinjamApi = inputFormatter.parse(item.tglPinjam)
                val millionSeconds = datePinjamApi?.time?.minus(Calendar.getInstance().timeInMillis)
                hariPenunggak.text = context.getString(
                    R.string.menunggak_x_hari,
                    millionSeconds!!.let { TimeUnit.MILLISECONDS.toDays(it).toString() })

                ingatkanPenunggakBeranda.setOnClickListener { item ->
                    Toast.makeText(item.context, "Diingatkan!", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): JatuhTempoViewHolder =
        JatuhTempoViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.item_penunggak_pengingat, parent, false
            )
        )

    override fun getItemCount(): Int = listJatuhTempo.size

    override fun onBindViewHolder(holder: JatuhTempoViewHolder, position: Int) {
        holder.bind(listJatuhTempo[position])
    }
}