package com.example.quiz.data.repository;

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

import com.example.quiz.data.model.RaceReport;
import com.example.quiz.data.model.ResponseError;
import com.example.quiz.data.remote.ReportApiService;
import com.example.quiz.utils.Result;
import com.google.gson.Gson;

import javax.inject.Inject;

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

public class RapportCourseRepository {
    private final ReportApiService reportApiService;

    @Inject
    public RapportCourseRepository(ReportApiService reportApiService) {
        this.reportApiService = reportApiService;
    }

    public LiveData<Result<RaceReport>> getRaceReport(String courseId) {
        MutableLiveData<Result<RaceReport>> raceReport = new MutableLiveData<>();
        raceReport.setValue(Result.loading());
        reportApiService.getRaceReport(courseId).enqueue(new Callback<RaceReport>() {
            @Override
            public void onResponse(Call<RaceReport> call, Response<RaceReport> response) {
                if(response.isSuccessful() && response.body() != null){
                    raceReport.postValue(Result.success(response.body()));
                }else{
                    if(response.code() == 404){
                        raceReport.postValue(Result.error("Aucun rapport disponible pour cette course"));
                    }else{
                        try {
                            String error = response.errorBody().string();
                            Gson gson = new Gson();
                            ResponseError errorResponse = gson.fromJson(error, ResponseError.class);
                            raceReport.postValue(Result.error(errorResponse.getMessage()));
                        } catch (Exception e) {
                            raceReport.postValue(Result.error("Erreur serveur"));
                        }
                    }
                }
            }

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