package com.kaixed.kchat.ui.activity

import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.kaixed.kchat.databinding.ActivityFriendListBinding
import com.kaixed.kchat.model.friend.FriendItem
import com.kaixed.kchat.ui.adapter.FriendListAdapter
import com.kaixed.kchat.utils.ConstantsUtil.getUsername
import com.kaixed.kchat.viewmodel.FriendListViewModel

class FriendListActivity : BaseActivity() {
    private lateinit var binding: ActivityFriendListBinding
    private val friendListViewModel: FriendListViewModel by viewModels()
    private var friendList: MutableList<FriendItem> = mutableListOf()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityFriendListBinding.inflate(layoutInflater)
        setContentView(binding.root)

        getFriendList(getUsername())

        if (friendList.isEmpty()) {
            binding.tvNothing.visibility = View.VISIBLE
        } else {
            binding.tvNothing.visibility = View.GONE
        }

        binding.recycleFriendList.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.recycleFriendList.adapter = FriendListAdapter(friendList, this)
    }

    private fun getFriendList(username: String) {
        friendListViewModel.getFriendList(username).observe(this) { value ->
            value?.let {
                friendList.addAll(value)
                binding.recycleFriendList.adapter?.notifyDataSetChanged()

                if (friendList.isEmpty()) {
                    binding.tvNothing.visibility = View.VISIBLE
                } else {
                    binding.tvNothing.visibility = View.GONE
                }
            }
        }
    }
}
