package com.kaixed.kchat.repository;

import static com.kaixed.kchat.network.NetworkInterface.ADD_FRIEND;
import static com.kaixed.kchat.network.NetworkInterface.SERVER_URL;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.kaixed.kchat.database.UserManager;
import com.kaixed.kchat.model.response.ApplyFriend;
import com.kaixed.kchat.network.NetworkRequest;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Author: kaixed
 * @Date: 2024/10/15 17:24
 * @Description: TODO
 */
public class AddFriendRepo {

    public MutableLiveData<ApplyFriend> addFriend(String contactId, String message) {
        MutableLiveData<ApplyFriend> applyFriendMutableLiveData = new MutableLiveData<>();

        RequestBody requestBody = new FormBody.Builder()
                .add("senderId", UserManager.getInstance().getUsername())
                .add("receiverId", contactId)
                .add("message", message)
                .build();

        new NetworkRequest().postAsync(SERVER_URL + ADD_FRIEND, requestBody, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                applyFriendMutableLiveData.postValue(null);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful() && response.body() != null) {
                    String responseBody = response.body().string();
                    ApplyFriend applyFriend = new Gson().fromJson(responseBody, ApplyFriend.class);
                    applyFriendMutableLiveData.postValue(applyFriend);
                } else {
                    applyFriendMutableLiveData.postValue(null);
                }
            }
        });

        return applyFriendMutableLiveData;
    }
}
