package com.kaixed.kchat.utils.handle

import com.kaixed.kchat.data.objectbox.ObjectBox.get
import com.kaixed.kchat.data.objectbox.entity.Contact
import com.kaixed.kchat.utils.Pinyin4jUtil
import io.objectbox.Box

/**
 * @Author: kaixed
 * @Date: 2024/11/19 16:11
 */
object ContactUtil {
    private val contactBox: Box<Contact> by lazy { get().boxFor(Contact::class.java) }

    fun handleContact(contact: Contact) {
        val contactLists = getDbContactLists()
        contactLists.add(contact)
        contact.apply {
            quanpin = Pinyin4jUtil.toPinyin(nickname)
            remark?.let {
                remarkquanpin = Pinyin4jUtil.toPinyin(remark!!)
            }
        }
        contactLists.forEachIndexed { index, item ->
            item.showHeader =
                (index == 0 || item.quanpin?.get(index) != contactLists[index - 1].quanpin?.get(
                    index - 1
                ))
        }
        contactBox.put(contactLists)
    }

    private fun getDbContactLists(): MutableList<Contact> {
        return contactBox.all.toMutableList()
    }
}
