package com.example.quiz.data.repository;

import android.util.Log;

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

import com.example.quiz.data.model.MiseInitiale;
import com.example.quiz.data.model.PariMise;
import com.example.quiz.data.model.ResponseError;
import com.example.quiz.data.remote.ApiService;
import com.example.quiz.data.remote.TokenManager;
import com.example.quiz.utils.Result;
import com.google.gson.Gson;

import java.util.List;

import javax.inject.Inject;

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

public class PariMiseRepository {
    private ApiService apiService;

    @Inject
    public PariMiseRepository(ApiService apiService, TokenManager tokenManager) {
        this.apiService = apiService;
    }

    public LiveData<Result<List<MiseInitiale>>> getBetInitMise() {
        MutableLiveData<Result<List<MiseInitiale>>> livePariMise = new MutableLiveData<Result<List<MiseInitiale>>>();
        livePariMise.setValue(Result.loading());
        apiService.getBetInitMise().enqueue(new Callback<List<MiseInitiale>>() {
            @Override
            public void onResponse(Call<List<MiseInitiale>> call, Response<List<MiseInitiale>> response) {
                if (response.isSuccessful()) {
                    livePariMise.postValue(Result.success(response.body()));
                }else{
                    try{
                        String error = response.errorBody().string();
                        Gson gson = new Gson();
                        ResponseError errorResponse = gson.fromJson(error, ResponseError.class);
                        livePariMise.postValue(Result.error(errorResponse.getMessage()));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            @Override
            public void onFailure(Call<List<MiseInitiale>> call, Throwable throwable) {
                livePariMise.postValue(Result.error(throwable.getMessage()));
            }
        });
        return livePariMise;
    }
}
