package com.kaixed.kchat.repository

import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.kaixed.kchat.model.friend.FriendItem
import com.kaixed.kchat.model.friend.FriendResponse
import com.kaixed.kchat.model.response.ApplyFriend
import com.kaixed.kchat.network.NetworkInterface.FRIEND_LIST
import com.kaixed.kchat.network.NetworkInterface.SERVER_URL
import com.kaixed.kchat.network.NetworkRequest
import okhttp3.Call
import okhttp3.Callback
import okhttp3.FormBody
import okhttp3.Response
import java.io.IOException

/**
 * @Author: kaixed
 * @Date: 2024/10/17 21:53
 * @Description: TODO
 */
class FriendListRepo {
    fun getFriendList(username: String): MutableLiveData<List<FriendItem>?> {
        val applyFriendMutableLiveData = MutableLiveData<List<FriendItem>?>()

        val requestBody = FormBody.Builder()
            .add("userid", username)
            .build()

        NetworkRequest().postAsync(SERVER_URL + FRIEND_LIST, requestBody, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                applyFriendMutableLiveData.postValue(null)
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful && response.body != null) {
                    val responseBody = response.body!!.string()
                    val friendList = Gson().fromJson(responseBody, FriendResponse::class.java)
                    applyFriendMutableLiveData.postValue(friendList.data)
                } else {
                    applyFriendMutableLiveData.postValue(null)
                }
            }
        })

        return applyFriendMutableLiveData
    }

}