package com.kaixed.kchat.repository;

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

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

import com.google.gson.Gson;
import com.kaixed.kchat.model.login.Login;
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 hui
 */
public class LoginRepository {

    public MutableLiveData<Login> login(String username, String password) {
        MutableLiveData<Login> loginResult = new MutableLiveData<>();

        RequestBody requestBody = new FormBody.Builder()
                .add("username", username)
                .add("password", password)
                .build();

        new NetworkRequest().postAsync(SERVER_URL + USER_LOGIN, requestBody, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                loginResult.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();
                    Login login = new Gson().fromJson(responseBody, Login.class);
                    loginResult.postValue(login);
                } else {
                    loginResult.postValue(null);
                }
            }
        });

        return loginResult;
    }
}
