package com.example.quiz.data.repository;

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

import com.example.quiz.data.model.PagedModel;
import com.example.quiz.data.model.PointDeVente;
import com.example.quiz.data.remote.ApiService;
import com.example.quiz.utils.Result;


import javax.inject.Inject;

import retrofit2.*;

public class PointDeVenteRepository {

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

    public LiveData<Result<PagedModel<PointDeVente>>> getPointsDeVente(String nom) {
        MutableLiveData<Result<PagedModel<PointDeVente>>> result = new MutableLiveData<>();
        result.setValue(Result.loading());

        apiService.getPointsDeVente(nom)
                .clone()
                .enqueue(new Callback<PagedModel<PointDeVente>>() {

            @Override
            public void onResponse(Call<PagedModel<PointDeVente>> call,
                                   Response<PagedModel<PointDeVente>> response) {

                if (response.isSuccessful() && response.body() != null) {
                    result.postValue(Result.success(response.body()));
                } else {

                    String errorMessage = "Erreur inconnue";

                    try {
                        if (response.errorBody() != null) {
                            errorMessage = response.errorBody().string();
                        }
                    } catch (Exception e) {
                        errorMessage = e.getMessage();
                    }

                    result.postValue(Result.error(errorMessage));
                }
            }

            @Override
            public void onFailure(Call<PagedModel<PointDeVente>> call, Throwable t) {
                result.postValue(Result.error(
                        t.getMessage() != null ? t.getMessage() : "Erreur réseau"
                ));
            }
        });

        return result;
    }

}
