package com.kaixed.kchat.ui.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.kaixed.kchat.data.objectbox.entity.ChatLists
import com.kaixed.kchat.databinding.ChatMainItemBinding
import com.kaixed.kchat.ui.activity.ChatActivity
import com.kaixed.kchat.ui.i.OnChatListItemClickListener
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter

/**
 * @Author: kaixed
 * @Date: 2024/10/27 18:22
 */
class ChatListAdapter(
    private val chatLists: List<ChatLists>,
    private val context: Context
) :
    RecyclerView.Adapter<ChatListAdapter.MyViewHolder?>() {
    private var onChatListItemClickListener: OnChatListItemClickListener? = null

    class MyViewHolder(val binding: ChatMainItemBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bindData(chatList: ChatLists) {
            binding.tvContent.text = chatList.lastContent
            binding.tvNickname.text = chatList.talkerId

            val instant = Instant.ofEpochMilli(chatList.timestamp)
            // 将时间戳转换为当前系统默认时区的时间
            val zdt = instant.atZone(ZoneId.systemDefault())
            // 格式化成小时：分钟格式
            val formatter = DateTimeFormatter.ofPattern("HH:mm")
            val formattedTime = zdt.format(formatter)
            binding.tvTimestamp.text = formattedTime
        }
    }

    fun setItemListener(i: OnChatListItemClickListener?) {
        this.onChatListItemClickListener = i
    }

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

    override fun onBindViewHolder(
        holder: MyViewHolder,
        @SuppressLint("RecyclerView") position: Int
    ) {
        holder.bindData(chatLists[position])
        holder.itemView.setOnClickListener {
            onChatListItemClickListener!!.onItemClick(chatLists[position].talkerId)

            context.startActivity(Intent(context, ChatActivity::class.java).apply {
                putExtra("friendId", chatLists[position].talkerId)
            })
        }
    }

    override fun getItemCount(): Int = chatLists.size
}
