package com.kaixed.kchat.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.kaixed.kchat.databinding.FragmentContactBinding
import com.kaixed.kchat.model.item.FriendItem
import com.kaixed.kchat.ui.adapter.FriendListAdapter
import com.kaixed.kchat.ui.base.BaseFragment
import com.kaixed.kchat.utils.ConstantsUtil.getUsername
import com.kaixed.kchat.viewmodel.FriendListViewModel

class ContactFragment : BaseFragment<FragmentContactBinding>() {

    private val friendListViewModel: FriendListViewModel by viewModels()

    private val friendAdapter: FriendListAdapter by lazy {
        FriendListAdapter(friendList, requireContext())
    }

    private var friendList: MutableList<FriendItem> = mutableListOf()

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

    override fun inflateBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentContactBinding {
        return FragmentContactBinding.inflate(inflater, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        getDefaultItem()
        binding.recycleFriendList.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        binding.recycleFriendList.adapter = friendAdapter
        getFriendList()
    }

    private fun getFriendList() {
        friendListViewModel.friendListLiveData.observe(viewLifecycleOwner) { friends ->
            friends?.let {
                friendList.addAll(friends)
                friendAdapter.notifyDataSetChanged()
            }
        }
        friendListViewModel.loadFriendList(getUsername())
    }

    private fun getDefaultItem() {
        friendList.add(FriendItem("新的朋友", "", remark = "hahah"))
        friendList.add(FriendItem("群聊", ""))
        friendList.add(FriendItem("标签", ""))
        friendList.add(FriendItem("公众号", ""))
        friendList.add(FriendItem("服务号", ""))
    }
}
