package com.example.modifier.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.modifier.adapter.BackupAdapter.BackupViewHolder
import com.example.modifier.baseTag
import com.example.modifier.data.BackupItem
import com.example.modifier.databinding.ItemBackupBinding
import java.text.SimpleDateFormat
import java.util.Date


class BackupAdapter(
    private val context: Context,
    private val backups: MutableList<BackupItem>,
    private val onItemClickListener: OnItemClickListener
) :
    RecyclerView.Adapter<BackupViewHolder>() {
    companion object {
        private const val TAG = "$baseTag/BackupAdapter"
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BackupViewHolder {
        val binding = ItemBackupBinding.inflate(
            LayoutInflater.from(
                context
            ), parent, false
        )
        return BackupViewHolder(binding)
    }

    interface OnItemClickListener {
        fun onRestoreClick(backup: BackupItem, position: Int)
        fun onDeleteClick(backup: BackupItem, position: Int)
    }

    @SuppressLint("DefaultLocale", "SetTextI18n", "SimpleDateFormat")
    override fun onBindViewHolder(holder: BackupViewHolder, position: Int) {
        val backup = backups[position]
        holder.binding.tvNumber.text = "+${backup.code} ${backup.number}"
        holder.binding.tvTime.text =
            SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(backup.createdAt))
        holder.binding.tvInfo.text = String.format(
            "MCC: %s, MNC: %s, Country: %s, SendCount: %d, Stock: %d",
            backup.mcc, backup.mnc, backup.country.uppercase(), backup.sendCount, backup.stock
        )
        holder.binding.btnRestore.setOnClickListener { v: View? ->
            onItemClickListener.onRestoreClick(backup, position)
        }
        holder.binding.btnDel.setOnClickListener { v: View? ->
            onItemClickListener.onDeleteClick(backup, position)
        }
    }

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

    inner class BackupViewHolder(var binding: ItemBackupBinding) : RecyclerView.ViewHolder(
        binding.root
    )
}
