package com.example.chatapp.adapters

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.chatapp.R
import com.example.chatapp.activities.ChatActivity
import com.example.chatapp.models.Conv
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class ConvRecyclerAdapter: RecyclerView.Adapter<ConvRecyclerAdapter.ViewHolder>() {

    var items: MutableList<Conv> = mutableListOf()
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_conv, parent, false)
        return ViewHolder(itemView)
    }

    override fun getItemCount() = items.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val conv = items[position]
        holder.bind(conv)
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val tvName : TextView = itemView.findViewById(R.id.tvConvName)
        val tvLast : TextView = itemView.findViewById(R.id.tvConvLastMsg)
        val tvHour : TextView = itemView.findViewById(R.id.tvHour)

        fun bind(conv: Conv) {
            tvName.text = conv.login
            tvLast.text = conv.lastMsg
            val sdf = SimpleDateFormat("HH:mm", Locale.getDefault())
            tvHour.text = sdf.format(Date(conv.timestamp))

            itemView.setOnClickListener {
                Intent(itemView.context, ChatActivity::class.java).also {
                    it.putExtra("conv", conv.login)
                    itemView.context.startActivity(it)
                }
            }
        }
    }

}