package com.kaixed.kchat.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.kaixed.kchat.model.item.FriendItem
import com.kaixed.kchat.repository.ContactRepo
import com.kaixed.kchat.utils.Pinyin4jUtil

/**
 * @Author: kaixed
 * @Date: 2024/10/17 22:02
 */
class FriendListViewModel : ViewModel() {
    private val contactRepo = ContactRepo()

    companion object {
        private const val TAG = "FriendListViewModel"
    }

    private val _friendListLiveData = MutableLiveData<List<FriendItem>?>()
    val friendListLiveData: LiveData<List<FriendItem>?> get() = _friendListLiveData

    fun loadFriendList(username: String) {
        contactRepo.getContactList(username).observeForever { friendList ->

            val uiFriendList = friendList?.map { networkItem ->
                mapToFriendItem(networkItem)
            }?.sortedWith { f1, f2 ->
                Pinyin4jUtil.compare(f1.nickname, f2.nickname)
            }?.toMutableList() // 确保是可变列表，以便后续更新 firstInSection

            uiFriendList?.forEachIndexed { index, item ->
                item.firstInSection =
                    (index == 0 || item.pinyin?.get(index) != uiFriendList[index - 1].pinyin?.get(
                        index - 1
                    ))
            }
//            Log.d(TAG, "loadFriendList: $uiFriendList")
            _friendListLiveData.value = uiFriendList
        }
    }

    private fun mapToFriendItem(response: com.kaixed.kchat.model.friend.FriendItem): FriendItem {
        val pinyin = Pinyin4jUtil.toPinyin(response.nickname)
        return FriendItem(
            nickname = response.nickname,
            username = response.username,
            remark = response.remark,
            avatarUrl = response.avatarUrl,
            pinyin = pinyin
        )
    }
}
