package com.example.quiz.data.repository;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.quiz.data.model.dtos.auth.LoginPayload;
import com.example.quiz.data.model.dtos.auth.LoginResponse;
import com.example.quiz.data.remote.ApiService;
import com.example.quiz.utils.Result;

import javax.inject.Inject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginRepository {
    private ApiService apiService;
    @Inject
    public LoginRepository(ApiService apiService) {
        this.apiService = apiService;
    }

    public LiveData<Result<LoginResponse>> login(LoginPayload loginPayload){
        MutableLiveData<Result<LoginResponse>> liveLogin = new MutableLiveData<Result<LoginResponse>>();
        liveLogin.setValue(Result.loading());
        apiService.login(loginPayload).enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                if(response.isSuccessful()){
                    liveLogin.postValue(Result.success(response.body()));
                }else{
                    liveLogin.postValue(Result.error(response.message()));
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable throwable) {
                liveLogin.postValue(Result.error(throwable.getMessage()));
            }
        });
        return liveLogin;
    }
}
